前言

传送门

正文

题目描述

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,10​5​​ ]), followed by N integer distances D​1 D​2​​ ⋯ D​N​​ , where Di 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 10​7
​​ .

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

思路:

  • 数组a[]存放相邻地点之间的距离,再对每个输入的距离进行累加即可得到整个环一周的长度,同时在输入数据的时候用dis[]数组记录下顺时针每个地点到第1个地点的距离
    注:
    a[i]表示第i个地点与第i+1个地点之间的距离
    dis[i]表示顺时针第1个地点到第i+1个地点之间的距离
  • 故两点之间距离可用diastance=dis[right-1]-dis[left-1]来表示(顺时针),再和sum-distance比较就可以得出最短的距离

参考题解:

#include<cstdio>
const int N=100010; 
int a[N]={0},dis[N]={0};
int main(){
	int num,sum=0,m,left,right,shortest;
	scanf("%d",&num);
	//a[i]表示第i个地点与第i+1个地点之间的距离
	//dis[i]表示顺时针第1个地点到第i+1个地点之间的距离 
	for(int i=1;i<=num;i++){
		scanf("%d",&a[i]);
		sum+=a[i];
		dis[i]=sum; 
	}
	scanf("%d",&m);
	while(m--){
		scanf("%d%d",&left,&right);
		if(right<left){
			int temp=left;
			left=right;
			right=temp;
		}
		int distance=dis[right-1]-dis[left-1];
		shortest=(distance>sum-distance)?sum-distance:distance;
		printf("%d\n",shortest);
	}
	return 0;
} 

后记

功名桥,世俗道,年少难免走一遭