Codeup——575 | 问题 E: 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.

输入

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

思路:题意就是用一系列的入口,这些入口组成了一个环,要求的是某个路口到某个路口的距离,我们不妨先把这个环的总长度求出来,这一步再输入从i到i+1路口距离时可以求得,同时在输入距离的过程中还要求第i个入口距离第一个入口的距离,这样是为了减少时间复杂度,不然后面通过不了。然后输入a口和b口时,如果b小则a,b进行交换,最后求出他们的距离,并用总长度减去所求距离可以得到另外一个距离(顺时针逆时针),将他们比较,最小的那个距离输出。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

int main()
{
	int n,m,o[100010],len[100010],a,b,l1,l2,i,l;
	while(scanf("%d",&n)!=EOF){
		l=0;
		memset(len,0,sizeof(len));
		for(i=1;i<=n;i++){
			scanf("%d",&o[i]);
			l+=o[i];
			len[i]=l-o[i];
		}
		scanf("%d",&m);
		for(int j=0;j<m;j++){
			scanf("%d%d",&a,&b);
			if(a>b) swap(a,b);
			l1=len[b]-len[a];
			l2=l-l1;
			printf("%d\n",min(l1,l2));
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44888152/article/details/106877927