PAT

甲级|1046.Shortest Distance

2018-11-08  本文已影响0人  yzbkaka

题目描述

The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.

输入描述

Each input file contains one test case. For each case, the first line contains an integer N (in [3,10​^5​​]), followed by N integer distances D​1​​ D​2​​ ⋯ D​N​​, where D​i​​ is the distance between the i-th and the (i+1)-st exits, and D​N​​ is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (≤10^​4​​), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 10​^7​​.

输出描述

For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.

输入例子

5 1 2 4 14 9
3
1 3
2 5
4 1

输出例子

3
10
7

我的代码

#include<stdio.h>
#define N 20000
int main(){
    int n,m,i,j,d[N],a[N],b[N],sum=0,sum1=0,sum2=0;
    scanf("%d",&n);  //输入N 
    for(i=1;i<=n;i++){  //从1开始输入 
        scanf("%d",&d[i]);  
        sum=sum+d[i];  //计算所有长度的和 
    }
    scanf("%d",&m);  //输入M 
    for(i=1;i<=m;i++){  //从1开始记组数 
        scanf("%d %d",&a[i],&b[i]);
    }
    
    for(i=1;i<=m;i++){
        for(j=a[i]<b[i]?a[i]:b[i];j<=((a[i]>b[i]?a[i]:b[i])-1);j++){
            sum1=sum1+d[j];  //计算顺时针的距离 
        }
        sum2=sum-sum1;  //得到逆时针的距离 
        if(sum1>=sum2){
        printf("%d\n",sum2);
      }
    else{
        printf("%d\n",sum1);
      }
       sum1=sum2=0;  //重置sun1与sum2 
    }
    return 0;   
} 

我的分析

这道题的英文描述不是很容易翻译,但是多读几遍题目理解之后还算是比较简单的题。我的思路是比较暴力的一种,就是先计算出两个结点(按照结点的序号由低到高)顺时针之间的距离sum1,然后拿整个圈的总距离sum-sum1得到sum2,最后比较输出sum1与sum2之间小的那个数即可。但是我这样的算法并不是满分,主要原因是如果对数组定义的大小不够的话容易发生段错误,过大的话则会超时。

AC代码

#include<stdio.h>
#define N 100005
int main(){
    int n,m,i,j,t,len[N],d[N],a[N],b[N],sum=0,sum1=0,sum2=0;  //新定义了一个len[]数组
    scanf("%d",&n);   
    for(i=1;i<=n;i++){ 
        scanf("%d",&d[i]);  
        sum=sum+d[i]; 
        len[i]=sum;  //len[i]表示第i+1个节点到第1个节点之间的距离
    }
    scanf("%d",&m); 
    for(i=1;i<=m;i++){  //在一个循环里面进行输入与计算
        scanf("%d %d",&a[i],&b[i]);
        if(a[i]<b[i]){
            t=a[i];
            a[i]=b[i];
            b[i]=t;
        }
        sum1=len[a[i]-1]-len[b[i]-1];
        sum2=sum-sum1; 
        if(sum1>=sum2){
        printf("%d\n",sum2);
      }
    else{
        printf("%d\n",sum1);
      }
       sum1=sum2=0; 
    }
    
    return 0;   
} 
上一篇下一篇

猜你喜欢

热点阅读