首页 > 代码库 > 一维树状数组

一维树状数组

Apple Tree http://poj.org/problem?id=3321

 1 #include<cstdio> 2 #include<cstring> 3 #define mt(a,b) memset(a,b,sizeof(a)) 4 const int M=100010; 5 struct G{ 6     struct E{ 7         int u,v,next; 8     }e[M<<1]; 9     int le,head[M];10     void init(){11         le=0;12         mt(head,-1);13     }14     void add(int u,int v){15         e[le].u=u;16         e[le].v=v;17         e[le].next=head[u];18         head[u]=le++;19     }20 }g;21 struct P{22     int l,r;23 }p[M];24 int Clock;25 void dfs(int u,int fa){26     p[u].l=++Clock;27     for(int i=g.head[u];~i;i=g.e[i].next){28         int v=g.e[i].v;29         if(v!=fa){30             dfs(v,u);31         }32     }33     p[u].r=Clock;34 }35 class One_Tree_Array { //一维树状数组36     typedef int typev;37     typev a[M];38 public:39     void init() {40         mt(a,0);41     }42     int lowb(int t) {43         return t&(-t);44     }45     void add(int i,typev v) {46         for(; i<M; a[i]+=v,i+=lowb(i));47     }48     typev sum(int i) {49         typev s=0;50         for(; i>0; s+=a[i],i-=lowb(i));51         return s;52     }53 }gx;54 int now[M];55 int main(){56     int n,m,u,v;57     while(~scanf("%d",&n)){58         g.init();59         for(int i=0;i<n-1;i++){60             scanf("%d%d",&u,&v);61             g.add(u,v);62             g.add(v,u);63         }64         Clock=0;65         dfs(1,-1);66         scanf("%d",&m);67         gx.init();68         for(int i=1;i<=n;i++){69             now[i]=1;70             gx.add(i,1);71         }72         while(m--){73             char op[4];74             scanf("%s%d",op,&u);75             if(op[0]==C){76                 gx.add(p[u].l,-now[u]);77                 now[u]=-now[u];78             }79             else{80                 printf("%d\n",gx.sum(p[u].r)-gx.sum(p[u].l-1));81             }82         }83     }84     return 0;85 }
View Code

 

 

 

end