poj3321Apple Tree(树状数组)
http://poj.org/problem?id=3321
刚一看题以为要建一颗树 看了下讨论说dfs
这里dfs遍历时设的标号很好 一个low一个high 包含了以这一节点为根节点的子树结点的所有标号
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<stdlib.h> 6 using namespace std; 7 #define N 100010 8 #define lowbit(x) (x&(-x)) 9 struct node 10 { 11 int u,v,next; 12 }ed[N<<1]; 13 int head[N],t,low[N],g,high[N],vis[N],re[N],f[N]; 14 void init() 15 { 16 t = 0; 17 memset(head,-1,sizeof(head)); 18 } 19 void add(int u,int v) 20 { 21 ed[t].u = u; 22 ed[t].v = v; 23 ed[t].next = head[u]; 24 head[u] = t; 25 t++; 26 } 27 void dfs(int u) 28 { 29 low[u] = ++g; 30 vis[u] = 1; 31 int i; 32 for(i = head[u] ; i != -1 ; i = ed[i].next) 33 { 34 int v = ed[i].v; 35 if(!vis[v]) 36 dfs(v); 37 } 38 high[u] = g; 39 } 40 void add1(int i,int da) 41 { 42 while(i<=g) 43 { 44 re[i]+=da; 45 i+=lowbit(i); 46 } 47 } 48 int getsum(int i) 49 { 50 int sum = 0; 51 while(i) 52 { 53 sum+=re[i]; 54 i-=lowbit(i); 55 } 56 return sum; 57 } 58 int main() 59 { 60 int i,j,k,n,m,a,b; 61 char s[5]; 62 init(); 63 scanf("%d",&n); 64 for(i = 1; i < n ; i++) 65 { 66 scanf("%d%d",&a,&b); 67 add(a,b); 68 add(b,a); 69 } 70 dfs(1); 71 for(i = 1 ; i <= g ; i++) 72 { 73 f[i] = -1; 74 add1(i,1); 75 } 76 scanf("%d",&m); 77 while(m--) 78 { 79 scanf("%s %d",s,&k); 80 if(s[0]=='Q') 81 { 82 printf("%d\n",getsum(high[k])-getsum(low[k]-1)); 83 } 84 else 85 { 86 add1(low[k],f[k]); 87 f[k] = f[k]*-1; 88 } 89 } 90 return 0; 91 }