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. Output For every inquiry, output the correspond answer per line.
Sample Input 3 1 2 1 3 3 Q 1 C 2 Q 1 Sample Output 3 2 Source POJ Monthly--2007.08.05, Huang, Jinsong
|
給你一顆樹,支援兩種操作
1.修改某一節點的權值
2.查詢子樹的權值(子樹中節點的個數)
很顯然可以用樹狀陣列維護
為什麼我的字型不能左對齊了。。。
1 #include<cstdio> 2 #include<cstring> 3 #include<cmath> 4 #include<algorithm> 5 #include<queue> 6 #define lb(x) x&(-x) 7 using namespace std; 8 const int MAXN=2*1e6+10; 9 const int INF=0x7fffff; 10 inline int read() 11 { 12 char c=getchar();int flag=1,x=0; 13 while(c<'0'||c>'9') {if(c=='-') flag=-1;c=getchar();} 14 while(c>='0'&&c<='9') x=x*10+c-48,c=getchar();return x*flag; 15 } 16 struct node 17 { 18 int u,v,nxt; 19 }edge[MAXN]; 20 int head[MAXN]; 21 int num=1; 22 inline void add_edge(int x,int y) 23 { 24 edge[num].u=x; 25 edge[num].v=y; 26 edge[num].nxt=head[x]; 27 head[x]=num++; 28 } 29 int n; 30 int in[MAXN],out[MAXN],cnt=0; 31 int tree[MAXN],have[MAXN]; 32 inline void pre() 33 { 34 memset(head,-1,sizeof(head)); 35 memset(have,1,sizeof(have)); 36 num=1;cnt=0; 37 } 38 int deep[MAXN]; 39 void dfs(int now) 40 { 41 in[now]=++cnt; 42 for(int i=head[now];i!=-1;i=edge[i].nxt) 43 dfs(edge[i].v); 44 out[now]=cnt; 45 } 46 int how[MAXN];//是否在樹上 47 inline void Interval_change(int pos,int val) 48 { 49 while(pos<=cnt) 50 { 51 tree[pos]+=val; 52 pos+=lb(pos); 53 } 54 } 55 inline int Interval_sum(int pos) 56 { 57 int ans=0; 58 while(pos) 59 { 60 ans+=tree[pos]; 61 pos-=lb(pos); 62 } 63 return ans; 64 } 65 int main() 66 { 67 while(scanf("%d",&n)==1) 68 { 69 pre(); 70 for(int i=1;i<=n-1;i++) 71 { 72 int x=read(),y=read(); 73 add_edge(x,y); 74 } 75 dfs(1); 76 for(int i=1;i<=n;i++) 77 Interval_change(in[i],1); 78 int q=read(); 79 for(int i=1;i<=q;i++) 80 { 81 char c[4];scanf("%s",c); 82 if(c[0]=='Q')//查詢 83 { 84 int pos=read(); 85 printf("%d\n",Interval_sum(out[pos])-Interval_sum(in[pos]-1)); 86 } 87 else 88 { 89 int pos=read(); 90 if(have[pos]) 91 Interval_change(in[pos],-1); 92 else Interval_change(in[pos],1); 93 have[pos]=!have[pos]; 94 } 95 } 96 } 97 return 0; 98 }