树状数组 (模板)

对着背影说爱祢 提交于 2020-03-21 23:43:55

树状数组的一维和二维模板

模板
int lowbit(int x){    return x & (-x);}void modify(int x,int add)//一维{      while(x<=MAXN)      {              a[x]+=add;            x+=lowbit(x);     }}int get_sum(int x){      int ret=0;     while(x!=0)      {               ret+=a[x];           x-=lowbit(x);       }      return ret;}void modify(int x,int y,int data)//二维{    for(int i=x;i<MAXN;i+=lowbit(i))        for(int j=y;j<MAXN;j+=lowbit(j))            a[i][j]+=data;}int get_sum(int x,int y){    int res=0;    for(int i=x;i>0;i-=lowbit(i))        for(int j=y;j>0;j-=lowbit(j))            res+=a[i][j];    return res;}

倆道模板题

hdu1166 地兵布阵 一维:

View Code
#include<stdio.h>#include<string.h>#include<stdlib.h>int c[50011],n;int lowbit(int x)//计算lowbit{    return x&(-x);}void add(int i,int val)//将第i个元素更改为val{    while(i<=n)    {        c[i]+=val;        i+=lowbit(i);    }}int sum(int i)//求前i项和{    int s=0;    while(i>0)    {        s+=c[i];        i-=lowbit(i);    }    return s;}int main(){int i ,j=0,a,b,v,t,num;char str[]="Add",str1[]="Sub",str2[]="End",sub1[6];scanf("%d",&t);while(t--){      scanf("%d",&n);     printf("Case %d:\n",++j);    memset(c,0,sizeof(c));   for(i=1;i<=n;++i)           {                 scanf("%d",&v);                add(i,v);           }   while(1)   {     scanf("%s",sub1);   if(!strcmp(str2,sub1))   break;if(!strcmp(sub1,str)){scanf("%d %d",&a,&b);add(a,b);}else if(!strcmp(sub1,str1)){scanf("%d %d",&a,&b);add(a,-b);}else {scanf("%d %d",&a,&b);printf("%d\n",sum(b)-sum(a-1));}}}return 0;}

 

hdu2642 Stars 二维:

View Code
#include<iostream>#include<algorithm>using namespace std;const int MAXN = 1010;int a[MAXN][MAXN];bool b[MAXN][MAXN];int lowbit(int x){    return x & (-x);}void modify(int x,int y,int data){    for(int i=x;i<MAXN;i+=lowbit(i))        for(int j=y;j<MAXN;j+=lowbit(j))            a[i][j]+=data;}int get_sum(int x,int y){    int res=0;    for(int i=x;i>0;i-=lowbit(i))        for(int j=y;j>0;j-=lowbit(j))            res+=a[i][j];    return res;}int main(){    int n,x,y,x1,y1;    char str[2];    scanf("%d",&n);    memset(a,0,sizeof(a));    memset(b,false,sizeof(b));    while(n--)    {        scanf("%s",str);        if(str[0]=='B')        {            scanf("%d %d",&x,&y);            x++;y++;            if(b[x][y]) continue;             modify(x,y,1);            b[x][y]=true;        }        else if(str[0]=='D')        {            scanf("%d %d",&x,&y);            x++;y++;            if(!b[x][y]) continue;            modify(x,y,-1);            b[x][y]=false;        }        else {            scanf("%d %d %d %d",&x,&x1,&y,&y1);            x++,y++;            x1++,y1++;                if(x>x1) swap(x,x1);            if(y>y1) swap(y,y1);            int ans=get_sum(x1,y1)-get_sum(x-1,y1)-get_sum(x1,y-1)+get_sum(x-1,y-1);            printf("%d\n",ans);        }    }    return 0;}



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!