1
10
1 2 3 4 5 6 7 8 9 10
Query 1 3
Add 3 6
Query 2 7
Sub 10 2
Add 6 3
Query 3 10
End
Case 1:
6
33
59
树状数组&线段树 入门模板题
树状数组写法树状数组简单介绍 http://blog.csdn.net/wang2332/article/details/70143534
#include
#include
#include
using namespace std;
#define N 50050
int a[N], c[N];
int n;
int lowbit(int x)
{
return x&(-x);
}
void update(int p, int x)
{
while(p <= n) {
c[p] += x;
p += lowbit(p);
}
}
int sum(int p)
{
int sum = 0;
while(p > 0) {
sum += c[p];
p -= lowbit(p);
}
return sum;
}
int main()
{
int T;
char str[10];
int u, v;
int k = 0;
scanf("%d",&T);
while(T--) {
int x;
memset(a,0,sizeof(a));
memset(c,0,sizeof(c));
scanf("%d",&n);
for(int i = 1;i <= n; i++) {
scanf("%d",&x);
a[i] += x;
update(i,x);
}
printf("Case %d:\n",++k);
while(~scanf("%s",str),strcmp(str,"End")) {
if(str[0] == 'A') {
scanf("%d%d",&u,&v);
a[u] += v;
update(u,v);
}
else if(str[0] == 'S') {
scanf("%d%d",&u,&v);
a[u] -= v;
update(u,-v);
}
else if(str[0] == 'Q') {
scanf("%d%d",&u,&v);
printf("%d\n",sum(v)-sum(u-1));
}
}
}
return 0;
}
线段树写法
线段树简单介绍
http://blog.csdn.net/wang2332/article/details/70145527
#include
using namespace std;
const int N = 400000+10;
struct node
{
int left, right;
int sum;
}tree[N];
void build(int l,int r,int step)
{
tree[step].left = l;
tree[step].right = r;
tree[step].sum = 0;
if(l == r) return ;
int mid = (l+r) >> 1;
build(l,mid,step<<1);
build(mid+1,r,step<<1|1);
}
void update(int l, int r, int value, int step)
{
tree[step].sum += value;
if(tree[step].left == tree[step].right)
return ;
int mid = (tree[step].left+tree[step].right) >> 1;
if(r <= mid) update(l,r,value,step<<1);
else if(l > mid) update(l,r,value,step<<1|1);
else {
update(l,mid,value,step<<1);
update(mid+1,r,value,step<<1|1);
}
}
int query(int l, int r,int step)
{
//找到叶子返回值
if(l==tree[step].left && r==tree[step].right) return tree[step].sum;
int mid = (tree[step].left+tree[step].right) >> 1;
//和更新类似
if(r <= mid) return query(l,r,step<<1);
if(l > mid) return query(l,r,step<<1|1);
else
return query(l,mid,step<<1)+query(mid+1,r,step<<1|1) ;
}
int main()
{
int T;
int u, v, k = 0;
char str[10];
scanf("%d",&T);
while(T--) {
int n, x;
scanf("%d",&n);
build(1,n,1);
for(int i = 1;i <= n; i++) {
scanf("%d",&x);
update(i,i,x,1);
}
printf("Case %d:\n",++k);
while(~scanf("%s",str),strcmp(str,"End")) {
scanf("%d%d",&u,&v);
if(str[0] == 'A') {
update(u,u,v,1);
}
if(str[0] == 'S') {
update(u,u,-v,1);
}
if(str[0] == 'Q') {
printf("%d\n",query(u,v,1));
}
}
}
return 0;
}