HDU1166 上好的线段树模板&&树状数组模板
自己写的第一棵线段树&第一棵树状数组 莫名的兴奋
线段树:
#include <cstdio>
using namespace std;
int cases,n,tree[200500],ql,qr;
char s[50];
void build(int l,int r,int num){
if(l==r){scanf("%d",&tree[num]);return;}
int mid=(l+r)/2;
build(l,mid,num*2);
build(mid+1,r,num*2+1);
tree[num]=tree[2*num]+tree[2*num+1];
}
int qu(int l,int r,int num){
if(ql<=l&&qr>=r)return tree[num];
int mid=(l+r)/2,sum=0;
if(mid>=ql)sum+=qu(l,mid,num*2);
if(mid<qr)sum+=qu(mid+1,r,num*2+1);
return sum;
}
void add(int l,int r,int num){
if(l==r){tree[num]+=qr;return;}
int mid=(l+r)/2;
if(mid>=ql)add(l,mid,num*2);
if(mid<ql)add(mid+1,r,num*2+1);
tree[num]=tree[2*num]+tree[2*num+1];
}
int main()
{
scanf("%d",&cases);
for(int ii=1;ii<=cases;ii++){
printf("Case %d:\n",ii);
scanf("%d",&n);
build(1,n,1);
while(scanf("%s",s)&&s[0]!='E'){
scanf("%d%d",&ql,&qr);
if(s[0]=='Q')printf("%d\n",qu(1,n,1));
else if(s[0]=='A')add(1,n,1);
else if(s[0]=='S')qr=-qr,add(1,n,1);
}
}
}
树状数组:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;
int cases,n,a[50005],c[50005];
char s[50];
int lowbit(int x){return x&(-x);}
void add(int x,int v)
{
while(x<=n)
{
c[x]+=v;
x+=lowbit(x);
}
}
int find(int x)
{
int ans=0;
while(x>0)
{
ans+=c[x];
x-=lowbit(x);
}
return ans;
}
int main()
{
scanf("%d",&cases);
for(int ii=1;ii<=cases;ii++)
{
printf("Case %d:\n",ii);
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
add(i,a[i]);
}
while(scanf("%s",s)&&s[0]!='E')
{
register int xx,yy;
scanf("%d%d",&xx,&yy);
if(s[0]=='Q')
printf("%d\n",find(yy)-find(xx-1));
else if(s[0]=='A')
add(xx,yy);
else if(s[0]=='S')
add(xx,-yy);
}
memset(c,0,sizeof(c));
memset(a,0,sizeof(a));
}
}