#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;
#define N 100000
#define step 1000
int main(int argc, char **argv) {
int n, m;
int dist[N] = {};
int ld[N/step] = {};
cin >> n;
int total = 0;
int sd = 0, s = 0, si = 0;
for(int i = 0; i < n; i ++) {
scanf("%d", dist+i);
total += dist[i];
sd += dist[i];
s ++;
if(s == step) {
ld[si++] = sd;
sd = 0;
s = 0;
}
}
cin >> m;
for(int i = 0; i < m; i ++) {
int c1, c2;
scanf("%d%d", &c1, &c2);
c1 --;
c2 --;
if(c1 > c2)
swap(c1, c2);
int d = 0;
if(c2 > c1) {
int d1 = c1, d2 = c2-1;
if(d2 - d1 < step) {
for(int i = d1; i <= d2; i ++)
d += dist[i];
}
else {
int p1 = d1/step + 1;
int p2 = d2/step;
for(int i = d1; i < p1*step; i ++)
d += dist[i];
for(int i = p1; i < p2; i ++)
d += ld[i];
for(int i = p2*step; i <= d2; i ++)
d += dist[i];
}
}
if((d<<1) > total)
d = total - d;
printf("%d\n", d);
}
return 0;
}
以下是按照链接中提供的优化算法实现的代码,比我的累加要高效多了。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#define N 100001
int main()
{
int dist[N] = {};
int n;
scanf("%d", &n);
for(int i = 2; i <= n; i ++) {
scanf("%d", &dist[i]);
dist[i] += dist[i-1];
}
int total;
scanf("%d", &total);
total += dist[n];
int m;
scanf("%d", &m);
for(int i = 0; i < m; i ++) {
int c1, c2;
scanf("%d%d", &c1, &c2);
if(c1 > c2)
swap(c1, c2);
int d1 = dist[c2] - dist[c1];
int d2 = total - d1;
printf("%d\n", min(d1, d2));
}
return 0;
}