6116 Problem E Shortest Distance (20)

問題 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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章