PAT_A 1046 Shortest Distance

PAT_A 1046 Shortest Distance

分析

本题是寻找最短路径,第 i 个数表示的是 i 至 i+1 的距离,与习惯的表示不同

题目的描述

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.

Input Specification:

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\).

Output Specification:

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

Sample Input:

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

Sample Output:

3
10
7

AC的代码

#include<bits/stdc++.h>

using namespace std;

int main(){
    int N;
    long long sum=0;
    cin>>N;
    vector<int> D(N);
    vector<long long > len(N,0);
    for(int i=0;i<N;i++){
        cin>>D[i];
        sum+=D[i];
        len[i]=sum;
    }
    int M;
    cin>>M;
    while(M){
        M--;
        long long a=0,b=0,d1=0,d2=0;
        cin>>a>>b;
        if(a>b){
//             for(int i=b-1;i<a-1;i++){
//                 d1+=D[i];
//             }
//             for(int i=a-1;i%N!=b-1;i++){
//                 d2+=D[i%N];
//             }
            d1=len[a-1]-len[b-1]-D[a-1]+D[b-1];
            d2=sum-d1;
            if(d2>d1)cout<<d1;
            else cout<<d2;
            
        }
        else if(a<b){
//             for(int i=b-1;i%N!=a-1;i++){
//                 d1+=D[i%N];
//             }
//             for(int i=a-1;i<b-1;i++){
//                 d2+=D[i];
//             }
            d1=-(len[a-1]-len[b-1]-D[a-1]+D[b-1]);
            d2=sum-d1;
            if(d2>d1)cout<<d1;
            else cout<<d2;
        }
        cout<<endl;
        
    }
    return 0;
}
posted @ 2022-01-24 22:38  ghosteq  阅读(23)  评论(0编辑  收藏  举报