A1046 Shortest Distance

A1046 Shortest Distance

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 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 (<=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

Code:

#pragma warning(disable: 4996)
#include <cstdio>
#include <cstdlib>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[]) {
int N;
scanf("%d", &N);

int *D = new int[N + 1];
D[0] = 0;
int sum = 0;
for (int i = 1; i <= N; i++) {//让下标对齐比较好理解
scanf("%d", &D[i]);
sum += D[i];
D[i] = sum;//是从1到i+1的总长度
}

int M;
scanf("%d", &M);

int Vi, Vj;
int clockwise = 0, countercw = 0;//顺时针逆时针
for (int i = 0; i < M; i++) {
scanf("%d %d", &Vi, &Vj);
//shoDist(N, D, Vi, Vj);开始写了个shoDist函数计算,但是最后一个测试点总是超时,后来选择了书上的算法
if (Vi > Vj)
swap(Vi, Vj);
clockwise = D[Vj - 1] - D[Vi - 1];
countercw = sum - clockwise;
printf("%d", clockwise < countercw ? clockwise : countercw);
if (i != M - 1)
printf("\n");
}

system("pause");
return 0;
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×