A1046 Shortest Distance (最短距离)
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 ⋯ D**N, where D**i is the distance between the i-th and the (i+1)-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 (≤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结尾无空行
题意:
有N个点,D1表示是1点到2点的距离,D2表示的是2点到3点的距离,D3。。。
M次循环,每次输入两个点,要求输出两点间的最短距离。
分析:
1.接收值,dis[i]从i~i+1 的距离变为从1~i+1点的距离
2.距离的两种计算方法:
(此处a>b,不满足条件的要先进行交换,目的是d1≮0)
顺序:d1=dis[b-1]-dis[a-1];
倒序:d2=sum-d1;
取最小距离
此题的关键点在于降低时间复杂度&&不要用结构体
此题时间复杂度是n,所以在第三个测试点时会报错
解决方法:原先的思路是把每个点的距离依次相加,但是需要while,产生的时间复杂度是n,第三个测试点会因为段错误而无法通过,解决方案是把原来的点k之间的距离变成1到k的距离,此时的时间复杂度是1
代码如下:
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=100005;
int dis[maxn];
int k,n,sum,a,b;
int main(){
scanf("%d",&k);
for(int i=1;i<k+1;i++){
scanf("%d",&dis[i]);
sum=sum+dis[i];
dis[i]=sum;
}
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d %d",&a,&b);
int d1=0;
if(a>b) swap(a,b);
d1=dis[b-1]-dis[a-1];
int d2=sum-d1;
printf("%d\n",min(d1,d2));
}
return 0;
}