1046 Shortest Distance (20分)

tech2022-10-20  107

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,​​]), followed by N integer distances D​1​​ D​2​​ ⋯ 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 (≤​​), 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 .

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个点之间的距离,要你求出某两个点之间的最短距离,这n个点形成一个环。

解题思路:

看到柳神的两个方向相加为总距离,我震惊了,果然大佬的思路巨便捷啊啊啊啊啊啊!

我的脑子什么时候能转的这么快就好了/(ㄒoㄒ)/~~

dis数组存储每个点到第一个点顺时针方向的距离,totalDis存储总距离。那么j到i的一个方向的距离就是abs(dis[j]-dis[i]),另一个方向的距离就是totalDis-abs(dis[j]-dis[i]),这两点之间的最短距离就是两个方向中更短的那个了。dis和totalDis在边输入的过程中边求得。

代码如下:

#include<iostream> #include<algorithm> #include<cmath> using namespace std; int N,M,totalDis = 0,temp; int dis[100005] = {0};//顺时针,每个点i到点1的距离 int main(){ scanf("%d",&N); for(int i = 2 ; i <= N ; i ++){ scanf("%d",&dis[i]); totalDis += dis[i]; dis[i] += dis[i-1]; } scanf("%d",&temp);//最后一个点到1的距离 totalDis += temp; scanf("%d",&M); while(M--){ int a,b; scanf("%d%d",&a,&b); printf("%d\n",min(abs(dis[b]-dis[a]),totalDis-abs(dis[b]-dis[a]))); } return 0; }

 

最新回复(0)