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]), followed by N integer distances D?1?? D?2?? ? D?N??, where D?i?? is the distance between the i-th and the (-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 (≤), 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 1.
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 #define _CRT_SECURE_NO_WARNINGS 2 #include <climits> 3 #include<iostream> 4 #include<vector> 5 #include<queue> 6 #include<map> 7 #include<set> 8 #include<stack> 9 #include<algorithm> 10 #include<string> 11 #include<cmath> 12 using namespace std; 13 int Dist[10000]; 14 int N, M; 15 int Sum; 16 void Ans(int i, int j) 17 { 18 int sum = 0; 19 if (i > j)Ans(j, i); 20 else 21 { 22 for (int k = i; k < j; k++) 23 sum += Dist[k]; 24 sum = (sum < (Sum - sum)) ? sum : Sum - sum; 25 cout << sum << endl; 26 } 27 } 28 int main() 29 { 30 31 cin >> N; 32 for (int i = 1; i <= N; i++) 33 { 34 cin >> Dist[i]; 35 Sum += Dist[i]; 36 } 37 cin >> M; 38 int v1, v2; 39 for (int i = 0; i < M; i++) 40 { 41 cin >> v1 >> v2; 42 Ans(v1, v2); 43 } 44 }
ac代码
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <climits> 3 #include<iostream> 4 #include<vector> 5 #include<queue> 6 #include<map> 7 #include<set> 8 #include<stack> 9 #include<algorithm> 10 #include<string> 11 #include<cmath> 12 using namespace std; 13 vector<int>Dist; 14 int sum; 15 int main() 16 { 17 int N; 18 cin >> N; 19 Dist.resize(N + 1); 20 for (int i = 1; i <=N; i++) 21 { 22 int temp; 23 cin >> temp; 24 sum += temp; 25 Dist[i] = sum; 26 } 27 int M; 28 cin >> M; 29 int v1, v2; 30 for (int i = 0; i < M; i++) 31 { 32 cin >> v1 >> v2; 33 if (v1 > v2) 34 swap(v1,v2); 35 int s1 = Dist[v2 - 1] - Dist[v1 - 1]; 36 int s2 = sum - s1; 37 if (s1 > s2) 38 cout << s2 << endl; 39 else 40 cout << s1 << endl; 41 } 42 }
原文地址:https://www.cnblogs.com/57one/p/12037128.html