1046 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,105]), 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 (≤104), 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 107.
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
题意
在一个环形的公路上有 n 个出口,现在给定一个序列 {D1 D2 ⋯ DN} ,其中 Di 表示第 i 个出口与第 i+1 个出口之间的距离, Dn 表示第 n 个出口与第 i 个出口之间的距离。
现在给定 m 个询问,需要我们输出给定两个出口之间的距离。
思路
这道题可以用前缀和的方法来做,创建一个数组 s 记录距离总和,其中 s[i] 表示第 1 个出口到第 i+1 个出口的距离之和。
这样一来,我们就可以通过 s[r-1]-s[l-1] 来计算出第 r 个出口与第 l 个出口之间的距离了。
但是,需要注意的是这是一个环形公路,所以还要计算 r...1...l 这段路径,然后与上面计算的路径作比较取最小值输出。而这段路径可以先计算出第 r 个路口到第 1 个路口的距离,即 s[n]-s[r-1] 。然后再计算第 1 个路口的距离到第 l 个路口的距离,即 s[l-1] 。两者相加就是这段距离之和,即 s[n]-s[r-1]+s[l-1] 。
故最终的答案就使求上面两个路径的最小值并输出,即 min(s[r-1]-s[l-1],s[n]-s[r-1]+s[l-1]) 。
代码
#include<bits/stdc++.h> using namespace std; const int N = 100010; int s[N]; int n, m; int main() { //输入数组元素并求前缀和 scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &s[i]); s[i] += s[i - 1]; } //进行询问 scanf("%d", &m); while (m--) { int l, r; scanf("%d%d", &l, &r); if (l > r) swap(l, r); printf("%d\n", min(s[r - 1] - s[l - 1], s[n] - s[r - 1] + s[l - 1])); } return 0; }