1046. 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.
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 思路 1.直接用累加求和,结果最后一项测试用例超时。
2.开一个二维数组暴力枚举出所有可能的情况,检测时直接输出对应情况,结果内存超了(最坏情况数组大小100001 * 100001)。
3.保存每一个目标点到起始点的road[i],那么任意两个点s,e的距离可以通过road[s]-road[e]计算出来,而不用再去一步步累加,所以不会超时。而且这种解决方案最坏情况开辟的数组大小为100001,不会超内存。 代码
#include<iostream>
#include<vector>
#include<math.h>
using namespace std; int main()
{
int N;
while(cin >> N)
{
vector<int> road(N + ,);
int sum = ;
for(int i = ;i <= N;i++)
{
int value;
cin >> value;
road[i + ] = road[i] + value;
sum += value;
}
int M;
cin >> M;
while(M--)
{
int s,e;
cin >> s >> e;
int path = abs(road[s] - road[e]);
cout << min(path,sum - path) << endl;
}
}
}