PAT (Advanced Level) 1046. Shortest Distance (20)

时间:2021-04-05 15:11:53

处理一下前缀和。

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<map>
#include<queue>
#include<string>
#include<vector>
using namespace std; const int maxn=+;
int a[maxn],n,m;
int pre[maxn];
int sum=; int main()
{
scanf("%d",&n); pre[]=;
for(int i=;i<=n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
pre[i]=pre[i-]+a[i];
}
scanf("%d",&m);
for(int i=;i<=m;i++)
{
int ans;
int li,ri; scanf("%d%d",&li,&ri);
if(li>ri) swap(li,ri);
ri--,ans=min(pre[ri]-pre[li-],sum-(pre[ri]-pre[li-]));
printf("%d\n",ans);
} return ;
}