标签:树状数组
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 20671 | Accepted: 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 has N forks which are connected by branches. Kaka numbers the forks by 1 to N and 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 integer N (N ≤ 100,000) , which is the number of the forks in the tree.
The following N - 1 lines each contain two integers u and v, which means fork u and fork v are connected by a branch.
The next line contains an integer M (M ≤ 100,000).
The following M lines each contain a message which is either
"C x" which means the existence of the apple on fork x has 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
"Q x" which means an inquiry for the number of apples in the sub-tree above the fork x, including the apple (if exists) on the fork x
Note the tree is full of apples at the beginning
Output
Sample Input
3 1 2 1 3 3 Q 1 C 2 Q 1
Sample Output
3 2
Source
#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-8 typedef __int64 ll; using namespace std; #define INF 0x3f3f3f3f #define N 100005 struct 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; }
标签:树状数组
原文地址:http://blog.csdn.net/u014737310/article/details/45456965