#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;
int a[N], S[N];
int main()
{
int n, m;
scanf("%d", &n);
for(int i = 1; i <= n; i ++)
{
scanf("%d", &a[i]);//读入已知的差分数组
S[i] = S[i-1] + a[i];//初始化前缀和数组
}
scanf("%d", &m);
while(m --)
{
int a, b;
scanf("%d %d", &a, &b);
if(a > b)
swap(a,b);
int res1 = S[b-1] - S[a-1];
int res2 = S[n] - res1;
printf("%d\n", min(res1, res2));
}
return 0;
}
甚至还可以不用开数组S[]:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;
int A[N], S[N]; //甚至都不用开数组S[]
int main()
{
int n, m;
scanf("%d", &n);
for(int i = 1; i <= n; i ++)
{
scanf("%d", &A[i]);//读入已知的差分数组
//S[i] = S[i-1] + a[i];//初始化前缀和数组
A[i] += A[i-1];
}
scanf("%d", &m);
while(m --)
{
int a, b;
scanf("%d %d", &a, &b);
if(a > b)
swap(a,b);
int res1 = A[b-1] - A[a-1];
int res2 = A[n] - res1;
printf("%d\n", min(res1, res2));
}
return 0;
}