Test instructions
Given a tree with roots, each node has an apple at the beginning;
There are two actions C x : Make the state of the X node change, the fruit becomes no, there is no;
Q x: Query The total number of fruits on the X-node pips tree;
N,m<=1^5
Exercises
The scope obviously cannot be searched, so we cannot enumerate when summing;
It can be thought of using a tree-like array to maintain and;
So the basic idea is to make the subtree each in an interval, and then the tree-like array is maintained;
This interval is made with DFS, which records the information of the whole subtrees tree in retrospect;
Specific or look at the code bar, deep search of the process and the like;
Card vector
Code:
#include <stdio.h> #include <string.h> #include <algorithm> #define N 100001using namespace Std;int Next[n<<1],head[n],to[n<<1];int tree[n],data[n],en[n],tot,cnt;bool A[N];char str[100];void Add (int x, int y) {to[++cnt]=y;next[cnt]=head[x];head[x]=cnt;} int lowbit (int k) {return k& (-K);} void Update (int k,int val) {while (k<=n) {tree[k]+=val;k+=lowbit (k);}} int query (int k) {int ret=0;while (k) {ret+=tree[k];k-=lowbit (k);} return ret;} void Dfs (int x,int pre) {int i,y;update (x,1); A[x]=1;data[x]=++tot;for (I=head[x];i;i=next[i]) {if ((Y=to[i])!=pre) {Dfs (y,x);}} En[x]=tot;} int main () {int n,m,i,j,k,x,y;scanf ("%d", &n), for (i=1;i<n;i++) {scanf ("%d%d", &x,&y), add (x, y), add (y,x );} DFS (1,0); scanf ("%d\n", &m), for (i=1;i<=m;i++) {scanf ("%s", str), if (str[0]== ' C ') {scanf ("%d", &x); if (A[x]) A[x]=0,update (data[x],-1); Elsea[x]=1,update (Data[x], 1);} ELSE{SCANF ("%d", &x);p rintf ("%d\n", Query (En[x])-query (data[x]-1));}} return 0;}
poj-3321 Apple Tree