初接触树状数组和线段树!!!!
AC代码如下:
树状数组代码
#include
#include
#include
using namespace std;
int c[100005];
int n,m;
int lowbit(int a)
{
return a&-a;
}
void add(int i,int a)
{
for(;i<=n;i+=lowbit(i)) c[i]+=a;
}
int sum(int a)
{
int ans=0;
for(;a>0;a-=lowbit(a))
ans+=c[a];
return ans;
}
int main()
{
int t;
int i,j,cas;
int a,b;
char st[10];
scanf("%d",&t);
for(cas=1;cas<=t;cas++)
{
memset(c,0,sizeof c);
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&a);
add(i,a);
}
printf("Case %d:\n",cas);
for(;;)
{
scanf("%s",st);
if(st[0]=='E')
break;
scanf("%d%d",&a,&b);
if(st[0]=='A')
add(a,b);
if(st[0]=='S')
add(a,-b);
if(st[0]=='Q')
printf("%d\n",sum(b)-sum(a-1));
}
}
return 0;
}
线段树
#include
#include
#include
using namespace std;
int n,m;
int num[100005];
struct H
{
int l,r,sum;
}trees[300005];
void build_trees(int jd,int l,int r)
{
trees[jd].l=l;
trees[jd].r=r;
if(l==r)
{trees[jd].sum=num[l];return ;}
int mid = (l+r)/2;
build_trees(jd*2,l,mid);
build_trees(jd*2+1,mid+1,r);
trees[jd].sum=trees[jd*2].sum+trees[jd*2+1].sum;
}
void update(int jd,int a,int b)
{
if(trees[jd].l==trees[jd].r)
trees[jd].sum+=b;
else {
int mid = (trees[jd].l+trees[jd].r)/2;
if(a<=mid) update(jd*2,a,b);
else update(jd*2+1,a,b);
trees[jd].sum=trees[jd*2].sum+trees[jd*2+1].sum;
}
}
int query(int jd , int l,int r)
{
if(l<=trees[jd].l&&r>=trees[jd].r)
return trees[jd].sum;
int ans=0;
int mid = (trees[jd].l+trees[jd].r)/2;
if(l<=mid) ans+=query(jd*2,l,r);
if(r>mid) ans+=query(jd*2+1,l,r);
return ans;
}
int main()
{
int t;
int i,j,cas;
int a,b;
char st[10];
scanf("%d",&t);
for(cas=1;cas<=t;cas++)
{
memset(num,0,sizeof num);
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&num[i]);
}
build_trees(1,1,n);
printf("Case %d:\n",cas);
for(;;)
{
scanf("%s",st);
if(st[0]=='E')
break;
scanf("%d%d",&a,&b);
if(st[0]=='A')
update(1,a,b);
if(st[0]=='S')
update(1,a,-b);
if(st[0]=='Q')
printf("%d\n",query(1,a,b));
}
}
return 0;
}