思路:
这道题时间卡的比较死,因此可以利用前缀和来计算两点距离不需要再次循环,从而大大的缩短时间,提高效率;其思路不难,值得注意的是a与b没说明大小,因此需要在写代码时比较一下。
AC:
#include <iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int dist[100010];
int sum[100010]={0};
int main()
{
int N;
cin>>N;
int total=0;
for(int i=1;i<=N;i++)
{
cin>>dist[i];
total+=dist[i];
sum[i]=sum[i-1]+dist[i];
}
int K;
cin>>K;
for(int i=1;i<=K;i++)
{
int a,b;
cin>>a>>b;
if(b<a)
{
swap(a,b);
}
int temp=sum[b-1]-sum[a-1];
cout<<min(temp,total-temp)<<endl;
}
return 0;
}