3.1小节—问题 E: Shortest Distance (20)

题目描述:

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, 100000]), followed by N integer distances D1 D2 … DN, where Di is the distance between the i-th and the (i+1)-st exits, and DN 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 (<=10000), 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 10000000.

输出

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<cstdio>
#include<cstdlib>
#include<cmath> 
int main(){
    int ArraySize,*Array,PairSize,i;
    int First,Second;              //记录读进的每对数 
    int ClocDis=0,AnticlocDis=0;   //记录顺时针,逆时针距离 
    int temp1=0,temp2=0,total=0;
    scanf("%d",&ArraySize);
    Array=(int*)malloc((ArraySize+1)*sizeof(int));
    Array[0]=0;
    for(i=1;i<=ArraySize;i++){
        scanf("%d",&Array[i]);   //构造相应大小的数组,并将距离存在数组中
        total+=Array[i];          ///计算总路程 
    } 
    scanf("%d",&PairSize);                      //读入有几对节点 
    while(PairSize--){
        scanf("%d %d",&First,&Second);
        for(i=0;i<First;i++)temp1+=Array[i];
        for(i=0;i<Second;i++)temp2+=Array[i];
        ClocDis=fabs(temp2-temp1);
        AnticlocDis=total-ClocDis;                   //计算顺时针与逆时针的距离 
        if(ClocDis>AnticlocDis)printf("%d",AnticlocDis);
        else printf("%d",ClocDis);
        if(PairSize)printf("\n");
        temp1=0;temp2=0;
    }                                //计算最短距离    
    free(Array);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42114379/article/details/82080098