1. 程式人生 > >【HihoCoder - 1880】地鐵環線 (字首和,水題,模擬)

【HihoCoder - 1880】地鐵環線 (字首和,水題,模擬)

題幹:

H市有一環線地鐵,一共包含N站,編號1~N。正向行駛的地鐵會按1 -> 2 -> 3 -> ... -> N -> 1的方向行駛,反向會按1 -> N -> N-1 -> ... -> 3 -> 2 -> 1的方向行駛。  

給定所有相鄰兩站之間地鐵行駛的時間(正向、反向時間相同),假設小Hi要從第X站到第Y站,請你判斷是小Hi是乘坐正向還是反向的列車用時更少?

Input

第一行包含兩個整數N和M,分別代表地鐵站數目和詢問的次數。

第二行包含N個整數A1, A2, ... AN,其中Ai代表從第i站正向行駛到下一站所用的時間。  

以下M行每行包含兩個整數X和Y,代表一個詢問。

1 ≤ N, M ≤ 100000  1 ≤ X, Y ≤ N  1 ≤ Ai ≤ 100000

Output

對於每組詢問,輸出一個整數表示最短時間。

Sample Input

5 2
1 2 3 4 5  
1 3  
1 5

Sample Output

3  
5

 

解題報告:

   相當於一個迴圈佇列就可以了、、、

AC程式碼:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define ll long long
#define pb push_back
#define pm make_pair
#define fi first
#define se second
using namespace std;
const int MAX = 2e5 + 5;
ll a[MAX];
ll sum[MAX];
int main()
{
	int n,m;
	cin>>n>>m;
	for(int i = 1; i<=n; i++) scanf("%lld",a+i),sum[i] = sum[i-1] + a[i]; 
	
	while(m--) {
		int l,r;
		scanf("%d%d",&l,&r);
		if(r < l) swap(l,r);
		ll tmp1 = sum[r-1] - sum[l-1];
		ll tmp2 = sum[n] - sum[r-1] + sum[l-1];
		printf("%lld\n",min(tmp1,tmp2));
	}
	
	
	return 0 ;
 }