题目描述
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<bits/stdc++.h>
#include<algorithm>
using namespace std;
int a[100005],dis[100005],sum=0;
int main(){
int n,i;
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
sum+=a[i];
dis[i]=sum;
}
int cn,left,right,j,k;
scanf("%d",&cn);
for(i=0;i<cn;i++){
scanf("%d %d",&left,&right);
if(left>right){
k=left;
left=right;
right=k;
}
int temp=dis[right-1]-dis[left-1];//顺时针走的总距离
printf("%d\n",min(temp,sum-temp));
}
}
注意
1、如果每次循环都计算没亮点的距离会超时的
2、temp=dis[right-1]-dis[left-1]; 一定减一,比如,计算1-2的距离,dis[2]=3,dis[1]=1,原本1-2的距离是1,但是如若计算dis[2]-dis[1]的话,就成了2,而只有dis[1]-dis[0]才能获得真正的答案
3、注意left,right大小问题