6116 Problem E Shortest Distance (20)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a845717607/article/details/89350556

问题 E: Shortest Distance (20)

时间限制: 1 Sec  内存限制: 32 MB

题目描述

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

经验总结

题意为,给出N个出口之间的距离,然后输入M对出口,计算这M对出口之间的最短距离,这一题不能在给定出口对时再依次累加两个出口之间的距离,一般来说,存在查询的题目都是静态查询,即查询的结果在输入结束时已经得出,或者经过简易的计算就可以得出,动态查询就是根据查询的内容再开始计算,在之前并没有对数据进行处理,很明显,动态查询在查询数目很多时,很容易超时,所以出现查询的题目,首先想到的应该是尽量减少从查询输入到输出结果之间的处理时间。

首先,在输入每个边的时候,就计算两个量,一个是这个环的总距离,这个用一个sum累加就可以实现,另一个,是第一个顶点距离各个顶点的距离,用一维数组实现,每个顶点的值等于输入的距离加上上一个顶点的值,初始将1这个顶点的值置为0,因为1到1本身就是0嘛。
然后,根据输入的两个顶点,将它们和顶点1之间的距离相减,就得到了其中一个距离,另一个距离通过环的总距离减去这个距离就能得到了,然后比较两个的大小,输出最小的,然后就完成啦ヽ( ̄▽ ̄)ノ

AC代码

#include <cstdio>
int main()
{
	int circle[100000],distance[100000];
	distance[1]=0;
	int n,m,sum=0;
	scanf("%d",&n);	
	int b,e,low,high,dis1,dis2;
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&circle[i]);
		sum+=circle[i];
		distance[i+1]=distance[i]+circle[i];
	}
	scanf("%d",&m);
	for(int j=0;j<m;j++)
	{
		scanf("%d%d",&b,&e);
		low=(b<e?b:e);
		high=(b>e?b:e);
		dis1=distance[high]-distance[low];
		dis2=sum-dis1;
		if(dis1<dis2)
			printf("%d\n",dis1);
		else
			printf("%d\n",dis2);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/a845717607/article/details/89350556