dfs序
1 /* 2 Source : POJ 3321 3 Problem : 每次改变树的点权,求子树点权和 4 Solution : dfs序 5 Date :2018-08-16-16.03 6 */ 7 8 // #include <bits/stdc++.h> 9 #include <cstdio> 10 #include <cstring> 11 #include <cstdlib> 12 #include <iostream> 13 #include <vector> 14 using namespace std; 15 16 typedef long long LL; 17 const int MAXN = 100005; 18 const LL MOD7 = 1e9+7; 19 20 inline int read() 21 { 22 int x=0;char ch=getchar(); 23 while (ch<'0' || ch>'9') ch=getchar(); 24 while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar(); 25 return x; 26 } 27 28 29 struct Edge 30 { 31 int u,v; 32 int next; 33 }edge[2*MAXN]; 34 int head[MAXN]; 35 int cnt; 36 37 // vector<int> g[MAXN]; 38 int n; 39 int in[MAXN]; 40 int out[MAXN]; 41 int pos[MAXN]; 42 int a[MAXN]; 43 int Clock; 44 int f[2*MAXN]; 45 46 void dfs(int u, int pre) 47 { 48 in[u]=++Clock; 49 pos[Clock]=u; 50 for (int i=head[u];i!=-1;i=edge[i].next) 51 { 52 int v=edge[i].v; 53 if (v==pre) continue; 54 dfs(v,u); 55 } 56 out[u]=Clock; 57 } 58 59 void init() 60 { 61 memset(f,0,sizeof(f)); 62 memset(head,-1,sizeof(head)); 63 cnt=0; 64 } 65 66 void addEdge(int u,int v) 67 { 68 edge[cnt].u=u;edge[cnt].v=v;edge[cnt].next=head[u];head[u]=cnt++; 69 } 70 71 inline int lowbit(int x) 72 { 73 return x&(-x); 74 } 75 76 void update(int x, int c) 77 { 78 while (x<=Clock) 79 { 80 f[x]+=c; 81 x+=lowbit(x); 82 } 83 } 84 85 int query(int x) 86 { 87 int sum=0; 88 for (;x;sum+=f[x],x-=lowbit(x)); 89 return sum; 90 } 91 92 int main() 93 { 94 #ifndef ONLINE_JUDGE 95 freopen("test.txt","r",stdin); 96 #endif // ONLINE_JUDGE 97 scanf("%d",&n); 98 { 99 int u,v; 100 // for (int i=1;i<=n;++i) g[i].clear(); 101 init(); 102 for (int i=1;i<n;++i) 103 { 104 u=read();v=read(); 105 // g[u].push_back(v); 106 // g[v].push_back(u); 107 addEdge(u, v); 108 addEdge(v, u); 109 } 110 Clock=0; 111 dfs(1,-1); 112 // init(); 113 for (int i=1;i<=n;++i) update(in[i],1),a[i]=1; 114 int Q; 115 scanf("%d",&Q); 116 char op[5]; 117 for (int i=1;i<=Q;++i) 118 { 119 scanf("%s%d",op,&u); 120 if (op[0]=='C') 121 { 122 update(in[u],-1*a[u]); 123 a[u]*=-1; 124 } 125 else 126 { 127 printf("%d\n",query(out[u])-query(in[u]-1)); 128 } 129 } 130 } 131 return 0; 132 }