標籤:sts 開始 enc miss change begin his query accept
Apple Tree
| Time Limit: 2000MS |
|
Memory Limit: 65536K |
| Total Submissions: 30869 |
|
Accepted: 9241 |
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
For every inquiry, output the correspond answer per line.
Sample Input
31 21 33Q 1C 2Q 1
Sample Output
32
題目大意:n個節點的蘋果樹,一開始每個節點都有1個蘋果,有兩個操作Q x,詢問以x為根的子樹的蘋果總和,
C x 為將x這個節點原本有蘋果就摘掉,沒蘋果就生一個蘋果。
題解:dfs序+樹狀數組
dfs序重要性質,一棵子樹的所有節點在dfs序裡是連續的一段,l[x]是x節點的dfs標號,如C X,修改的是l[x]
1A好開心~=u=
代碼:
#include<iostream>#include<cstdio>#include<cstring>#define maxn 100002using namespace std;int n,m,sumedge,tim_node;int head[maxn],l[maxn],r[maxn],tr[maxn],sum[maxn];struct Edge{ int x,y,nxt; Edge(int x=0,int y=0,int nxt=0): x(x),y(y),nxt(nxt){}}edge[maxn<<1];void add(int x,int y){ edge[++sumedge]=Edge(x,y,head[x]); head[x]=sumedge;}void dfs(int x,int fa){ l[x]=++tim_node; for(int i=head[x];i;i=edge[i].nxt){ int v=edge[i].y; if(v==fa)continue; dfs(v,x); } r[x]=tim_node;}int lowbit(int x){ return x&(-x);}void update(int x,int v){ for(int i=x;i<=n;i+=lowbit(i))tr[i]+=v;}int query(int x){ int w=0; for(int i=x;i;i-=lowbit(i))w+=tr[i]; return w;}int main(){ scanf("%d",&n); for(int i=1;i<n;i++){ int x,y; scanf("%d%d",&x,&y); add(x,y);add(y,x); } for(int i=1;i<=n;i++)update(i,1); dfs(1,-1); scanf("%d",&m); for(int i=1;i<=m;i++){ char od[3];int x; cin>>od>>x; if(od[0]==‘Q‘){ int ans=query(r[x])-query(l[x]-1); printf("%d\n",ans); }else{ if(!sum[x]){ sum[x]=1; update(l[x],-1); }else{ sum[x]=0; update(l[x],1); } } } return 0;}
poj 3321 Apple Tree