2016-05-29 17:03:51
Title Link: POJ 3321 Apple Tree
Main topic:
To a tree, at first each node has a weight value of 1.
Two kinds of operations:
1.C x Reverse the weight of the X-node
2.Q x the weights and values of the subtree with x as the root tree
Solution:
Maintaining DFS ordering with a tree-like array
To be aware of:
1. An array is required to store the weight of each node for easy modification
1 //Apple Tree (POJ no.3321)2 //tree-like array3#include <stdio.h>4#include <algorithm>5#include <string.h>6 using namespacestd;7 Const intmaxn=100010;8 structEdge9 {Ten intto ; One intNext; A Edge () {} -EdgeintTo,intnext): To, Next (next) {} - }; theEdge n[maxn*2]; - intHEAD[MAXN]; - intCNT; - Charnow[5]; + BOOLP[MAXN]; - voidInsertintXinty) + { An[++cnt]=Edge (Y,head[x]); athead[x]=CNT; -n[++cnt]=Edge (X,head[y]); -head[y]=CNT; - return ; - } - intn,m; in intDFN[MAXN]; - intSON[MAXN]; to intBIT[MAXN]; + intLowbit (intx) - { the returnx&-x; * } $ voidAddintLocintval)Panax Notoginseng { - for(intI=loc;i<=n;i+=lowbit (i)) bit[i]+=Val; the return ; + } A intQueryintLoc) the { + intsum=0; - for(intI=loc;i;i-=lowbit (i)) sum+=Bit[i]; $ returnsum; $ } - intIndex; - voidDFS (intx) the { -dfn[x]=++Index;Wuyison[x]=x; the for(intI=head[x];i;i=n[i].next) - { Wu if(dfn[n[i].to]==0) - { About DFS (n[i].to); $son[x]=son[n[i].to]; - } - } - return ; A } + intMain () the { -scanf"%d",&N); $ for(intI=1; i<n;i++) the { the intx, y; thescanf"%d%d",&x,&y); the Insert (x, y); -Add (I,1); in } theAdd (N,1); theDFS (1); Aboutscanf"%d",&M); the for(intI=1; i<=m;i++) the { the intx; +scanf"%s%d",now,&x); - if(now[0]=='Q') the {Bayiprintf"%d\n", query (Dfn[son[x]])-query (dfn[x]-1)); the } the Else - { -p[x]^=1; the if(p[x]==1) the { theAdd (dfn[x],-1); the } - ElseAdd (Dfn[x],1); the } the } the return 0;94}
POJ 3321 Apple Tree