一开始的思路是直接用for遍历,但是会爆时间,后来参考了一下大神的代码改进了一下。
换用动态规划的思路去做就会节省一层for的时间。
题目描述
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.
输入
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.
输出
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
样例输入:
5 1 2 4 14 9
3
1 3
2 5
4 1
样例输出:
3
10
7
话不多说,直接上代码:
#include <cstdio>
const int N=100010;
int a[N];
int main (){
int n,m;
scanf("%d",&n);
long long int sum=0;
a[0]=0;
//由环拆成线,多加一个节点;
for(int i=1;i<n+1;i++){
scanf("%d",&a[i]);
sum+=a[i];
a[i]+=a[i-1];
}
scanf("%d",&m);
while(m--){
int x,y;
scanf("%d%d",&x,&y);
long long temp=0;
if(x>y){
temp=a[x-1]-a[y-1];
}
else{
temp=a[y-1]-a[x-1];
}
if(temp>sum-temp) temp=sum-temp;
printf("%d\n",temp);
}
}
为了便于理解数组下标和题目中的编号的区别,可以结合下面的图示理解,其中(1)表示第一个输入的距离,以此类推。左图为题目的抽象,右图是用数组存储的形式。