[poj3321]Apple Tree(dfs序+树状数组)

Apple Tree
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 26762   Accepted: 7947

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?

[poj3321]Apple Tree(dfs序+树状数组)

Input

The first line contains an integer N (N ≤ 100,000) , which is the number of the forks in the tree.
The following N - 1 lines each contain two integers u and v, which means fork u and fork v are connected by a branch.
The next line contains an integer M (M ≤ 100,000).
The following M lines each contain a message which is either
"x" which means the existence of the apple on fork x has been changed. i.e. if there is an apple on the fork, then Kaka pick it; otherwise a new apple has grown on the empty fork.
or
"x" which means an inquiry for the number of apples in the sub-tree above the fork x, including the apple (if exists) on the fork x
Note the tree is full of apples at the beginning

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
 
继续继续继续
 
dfs序嘛
原来之前理解的是错的
其实就是tarjan的dfn与low数组
得出dfn与low后
dfn[i]是起点,low[i]是终点,中间的一段就是点i的子树了
这样dfs序就可以“方便的维护子树”
而对于大部分按照dfs序维护序列的题,与树状数组是相当好的组合
这道题差不多是裸题了,多开一个表示当前节点状态的数组就可以了
 #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int ap[],bit[];
int bg[],ed[],cnt=;
int n;
typedef struct{
int to,nxt;
}edge;
edge gra[];
int head[],num=;
int add(int frm,int to){
gra[++num].nxt=head[frm];
gra[num].to=to;
head[frm]=num;
return ;
}
int dfs(int u,int fa){
bg[u]=++cnt;
int j;
for(j=head[u];j;j=gra[j].nxt){
if(gra[j].to!=fa)dfs(gra[j].to,u);
}
ed[u]=cnt;
return ;
}
int lb(int x){
return x&(-x);
}
int c(int x){
int num=ap[x];
x=bg[x];
while(x<=n){
bit[x]+=num;
x+=lb(x);
}
return ;
}
int q(int x){
int a1=,a2=;
int e=ed[x];
while(e){
a1+=bit[e];
e-=lb(e);
}
int b=bg[x]-;
while(b){
a2+=bit[b];
b-=lb(b);
}
return a1-a2;
}
int main(){
scanf("%d",&n);
for(int i=;i<n;i++){
int x,y;
scanf("%d %d",&x,&y);
add(x,y);
add(y,x);
}
dfs(,);
for(int i=;i<=n;i++){
ap[i]=;
c(i);
}
int m;
scanf("%d",&m);
for(int i=;i<=m;i++){
char in[];
int x;
scanf("%s %d",in,&x);
if(in[]=='C'){
ap[x]*=-;
c(x);
}
else printf("%d\n",q(x));
}
return ;
}

睡觉

上一篇:iOS 导航控制器如何随意push和pop 想要在 A push B 后, B 在push 到 D ,然后从 D pop 到 C ,在从 C pop 的A


下一篇:IOS开发UI篇—导航控制器属性和基本使用