刚刚做完4351的线段树……想起当初入门的线段树水题…于是迅速干掉!
裸裸的超标准单点更新线段树格式
想学线段树的同学,建议百度线段树完全版,如果完全版看不懂的话就看旧版吧。旧版好懂一点
刚刚看了树状数组……用来再次刷了一次这道题……代码下面=.,= 2012.9.24
#include <iostream>
#include <cstdio>
#include <cmath>
const int maxx = 50000;
using namespace std;
int num[maxx<<2];
struct note
{
int ld,rd;
int key;
} point[maxx<<2];
int build(int left,int right,int idx)
{
point[idx].ld = left;
point[idx].rd = right;
if(left==right)
{
point[idx].key = num[left];
return point[idx].key;
}
int mid = (left+right)/2;
return point[idx].key = build(left,mid,idx<<1) + build(mid+1,right,idx<<1|1);
}
void add(int dir,int idx,int x)
{
point[idx].key += x;
int mid = (point[idx].ld+point[idx].rd)/2;
if(point[idx].ld == point[idx].rd)
return;
if(dir>mid)
add(dir,idx<<1|1,x);
else if(dir<=mid)
add(dir,idx<<1,x);
}
int out(int left,int right,int idx)
{
if(point[idx].ld==left&&point[idx].rd==right)
return point[idx].key;
int mid = (point[idx].ld+point[idx].rd)/2;
if(right<=mid)
return out(left,right,idx<<1);
else if(left>mid)
return out(left,right,idx<<1|1);
else
return out(left,mid,idx<<1) + out(mid+1,right,idx<<1|1);
}
int main()
{
// freopen("123.txt","r",stdin);
int t;
scanf("%d",&t);
for(int k=1;k<=t;k++)
{
printf("Case %d:\n",k);
int n;
scanf("%d",&n);
for(int i=1; i<=n; i++)
scanf("%d",&num[i]);
build(1,n,1);
char ch[20];
while(scanf("%s",ch),ch[0]!='E')
{
int a,b;
scanf("%d%d",&a,&b);
if(ch[0]=='A')
add(a,1,b);
else if(ch[0]=='Q')
printf("%d\n",out(a,b,1));
else if(ch[0]=='S')
add(a,1,-b);
}
}
return 0;
}
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int mx = 50100;
int val[mx];
int n;
inline int lowbit(int x)
{
return x & (-x);
}
void update(int dex , int add)
{
while(dex <= n)
{
val[dex] += add;
dex += lowbit(dex);
}
}
int get_sum(int dex)
{
int ans = 0;
while(dex > 0)
{
ans += val[dex];
dex -= lowbit(dex);
}
return ans;
}
int main()
{
// freopen("1164.txt","r",stdin);
int t;
int cases = 0;
scanf("%d",&t);
while(t--)
{
printf("Case %d:\n",++cases);
memset(val, 0, sizeof(val));
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
int tem;
scanf("%d",&tem);
update(i , tem);
}
char ch[20];
while(scanf("%s",ch),ch[0]!='E')
{
int a,b;
scanf("%d %d",&a,&b);
if(ch[0] == 'Q')
printf("%d\n",get_sum(b) - get_sum(a-1));
else if(ch[0] == 'A')
update(a , b);
else if(ch[0] == 'S')
update(a , -b);
}
}
return 0;
}