1046. Shortest Distance (20)
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 ... 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.
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
分析:
- 题目:城市之间高速依次连成一个圈,给出相邻距离,求给定城市的最短距离。
- 解题:输入时,记录距离和,在求两个城市的距离是,对记录的sumi sumj做差,求余。有两种情况,由于是个圈必定左边一条,右边一条,要比较所求距离结果,输出最短。
code:
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
vector<int>dis;
int main()
{
freopen("in","r",stdin);
int N,M,tmp,tmp2,sum;
scanf("%d",&N);
sum=0;
dis.push_back(sum);//city0 起始距离0
for(int i=0;i<N;i++)
{
scanf("%d",&tmp);
sum+=tmp;
dis.push_back(sum);//记录距离和,求两个城市距离通过做差求得
}
scanf("%d",&M);
int a,b;
for(int i=0;i<M;i++)
{
scanf("%d%d",&tmp,&tmp2);
tmp--;tmp2--;//纠正数组下标
a=(dis[tmp]-dis[tmp2]+sum)%sum;//避免出现负数,求补
b=(dis[tmp2]-dis[tmp]+sum)%sum;
if(a<b)
printf("%d\n",a);
else
printf("%d\n",b);
}
return 0;
}
- AC: