POJ 3321 Apple Tree(树状数组)

Apple Tree

Time Limit:2000MSMemory Limit:65536K

Total Submissions:20671Accepted:6257

Description

There is an apple tree outside of kaka’s house. Every autumn, a lot of apples will grow in the tree. Kaka likes apple very much, so he has been carefully nurturing the big apple tree.

The tree hasNforks which are connected by branches. Kaka numbers the forks by 1 toNand the root is always numbered by 1. Apples will grow on the forks and two apple won’t grow on the same fork. kaka wants to know how many apples are there in a sub-tree, for his study of the produce ability of the apple tree.

The trouble is that a new apple may grow on an empty fork some time and kaka may pick an apple from the tree for his dessert. Can you help kaka?

Input

The first line contains an integerN(N≤ 100,000) , which is the number of the forks in the tree.The followingN- 1 lines each contain two integersuandv, which means forkuand forkvare connected by a branch.The next line contains an integerM(M≤ 100,000).The followingMlines each contain a message which is either"Cx" which means the existence of the apple on forkxhas been changed. i.e. if there is an apple on the fork, then Kaka pick it; otherwise a new apple has grown on the empty fork.or"Qx" which means an inquiry for the number of apples in the sub-tree above the forkx, including the apple (if exists) on the fork xNote the tree is full of apples at the beginning

Output

For every inquiry, output the correspond answer per line.

Sample Input

31 21 33Q 1C 2Q 1

Sample Output

32

Source

, Huang, Jinsong

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<queue>#include<stack>#include<vector>#include<set>#include<map>#define L(x) (x<<1)#define R(x) (x<<1|1)#define MID(x,y) ((x+y)>>1)#define eps 1e-8typedef __int64 ll;using namespace std;#define INF 0x3f3f3f3f#define N 100005struct stud{//坑爹的地方是用vector会超时 int to,next;}e[N*2];int e_num;int head[N];int c[N];int n;int le[N],ri[N];int num;int a[N];int vis[N];inline int lowbit(int x){return x & (-x);}void dfs(int x){le[x]=++num;int i;for(i=head[x];i!=-1;i=e[i].next){int to=e[i].to;dfs(to);} ri[x]=num;}void update(int x,int va){while(x<=n){c[x]+=va;x+=lowbit(x);}}int sum(int x){int s=0;while(x>0){s+=c[x];x-=lowbit(x);} return s;}int main(){int i,j;scanf("%d",&n);{for(i=0;i<=n;i++)c[i]=0;int u,v;i=n-1;e_num=0;memset(head,-1,sizeof(head));while(i–){scanf("%d%d",&u,&v);e[e_num].to=v;e[e_num].next=head[u];head[u]=e_num++;}for(i=1;i<=n;i++){a[i]=1;update(i,1);}num=0;dfs(1);scanf("%d",&u);char ch[10];while(u–){scanf("%s%d",ch,&v);if(ch[0]=='Q'){int lee=sum(le[v]-1);int rii=sum(ri[v]);printf("%d\n",rii-lee);}else{if(a[le[v]]) update(le[v],-1);else update(le[v],1);a[le[v]]=!a[le[v]];}}}return 0;}

,不敢接受失败的人,往往是那些追求完美的人,

POJ 3321 Apple Tree(树状数组)

相关文章:

你感兴趣的文章:

标签云: