环形地铁(前缀和)

Description

有一环形地铁,一共有nn站,编号1-n1−n。

正向行驶地铁会按照1->2->3->⋯->n->1的方向行驶

反向则按照1->n->⋯->3->2->1的方向行驶。

给定相邻两站之间的地铁行驶时间(正向、反向时间相同),现在有mm组询问,每次询问从第xx站到第yy站的最短时间。

Input

输入只有一组数据。

第一行包含两个整数n,mn,m,分别表示地铁站数和询问次数

第二行有nn个整数a1,a2,…,ana1,a2,…,an,其中aiai表示从第ii站正向行驶到下一站的时间。

接下来mm行,每行两个整数xx和yy,代表询问从第xx站到第yy站的最短时间。

(1le n,m,ai le 200000,1 le x,yle n)(1≤n,m,ai≤200000,1≤x,y≤n)

Output

输出mm行,第ii行输出第ii次询问的答案

Sample Input 1 

5 2
1 2 3 4 5  
1 3  
1 5

Sample Output 1

3
5

思路:要考虑无向的最短距离,用前缀和来表示,不然可能会超时

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>

using namespace std;
long long int a[200005];
long long int sum[200005];
int main()
{
	int n,m;
	cin>>n>>m;
	for(int t=0;t<n;t++)
	{
		scanf("%lld",&a[t]);
	}
	sum[0]=0;
	sum[1]=a[0];
	for(int t=2;t<=n;t++)
	{
		sum[t]=a[t-1]+sum[t-1]; 
	}
	
	int l,r;
	for(int t=0;t<m;t++)
	{
		scanf("%d%d",&l,&r);
		if(l>r)
		{
			int temp=l;
			l=r;
			r=temp;
			
		}
		long long int s=min((sum[r-1]-sum[l-1]),(sum[l-1]-sum[0]+sum[n]-sum[r-1]));
		printf("%lld
",s);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Staceyacm/p/10781825.html