PAT-A1046 Shortest Distance (20分)
注:没有经过预处理dis数组和sum会很容易超时。在极端情况下需要遍历这个数组。
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n = 0;
int sum = 0;
int num_arr[100005] ,dis[100005];
cin >> n;
//初始数据
for (int i = 0; i < n; i++) {
cin >> num_arr[i];
//预处理dis[]为是否超时的关键
sum += num_arr[i];
dis[i] = sum;
//cout << dis[i] << " " << endl;
}
int times = 0;
int start, up = 0;
cin >> times;
for (int i = 0; i < times; i++) {
cin >> start;
cin >> up;
if (start > up) {
swap(start, up);
}
//cout << "start:" << start << " end:" << up << endl;
start = start - 2;
up = up - 2;
int res = 0;
int temp = 0;
dis[-1] = 0;
temp = dis[up] - dis[start];
res = min(temp, sum - temp);
cout << res << endl;
}
return 0;
}