比赛 |
线段数树状数组 |
评测结果 |
AAAAAAAWWW |
题目名称 |
求和问题 |
最终得分 |
70 |
用户昵称 |
忆轩 |
运行时间 |
0.415 s |
代码语言 |
C++ |
内存使用 |
0.90 MiB |
提交时间 |
2018-06-17 10:34:21 |
显示代码纯文本
#include<algorithm>
#include<cstdio>
#define N 10005
#define LL long long
using namespace std;
int n, m, x, y;
struct nond {
int ll, rr;
LL sum;
}tree[4*N];
void up(int now) {
tree[now].sum = tree[now*2].sum+tree[now*2+1].sum;
}
void build(int now, int l, int r) {
tree[now].ll = l; tree[now].rr = r;
if(l == r) {
scanf("%d", &tree[now].sum);
return ;
}
int mid = (l+r) / 2;
build(now*2, l, mid);
build(now*2+1, mid+1, r);
up(now);
}
LL query(int now, int l, int r) {
if(tree[now].ll==l && tree[now].rr==r) return tree[now].sum;
int mid = (tree[now].ll+tree[now].rr) / 2;
if(l<=mid && mid<r) return query(now*2, l, mid)+query(now*2+1, mid+1, r);
else if(r<=mid) return query(now*2, l, r);
else return query(now*2+1, l, r);
}
int main() {
freopen("sum.in","r",stdin);
freopen("sum.out","w",stdout);
scanf("%d", &n);
build(1, 1, n);
scanf("%d", &m);
for(int i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
printf("%d\n", query(1, x, y));
}
fclose(stdin); fclose(stdout);
return 0;
}