poj3321 dfs序的应用,树上求子树和
作者:互联网
Apple Tree POJ3321
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?
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
"C 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
"Q 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
题目大意:给定一个树,树上首先有一个苹果,然后n次操作,其中Q查询,C非操作(有->无,无->有)
题目解读:利用dfs序将树转换成区间,然后利用树状数组或者线段树进行维护区间和
#include<cstdio>
#include<iostream>
#define fore(i,a,b) for(int i=a;i<=b;i++)
const int SIZE=(int)1e5+5;
bool vis[SIZE];
int head[SIZE],edge[SIZE],ver[SIZE],next[SIZE],tot;
// 表头定位从x出发的所有边,edge边权值,ver指向的序号y,next指向下一个边
int dfsline[SIZE],in[SIZE],out[SIZE],time;
int Tree[SIZE];
int fork[SIZE];
void add(int x,int y,int val){
ver[++tot] = y,edge[tot] = val;//插入新边并修改权值
next[tot]=head[x],head[x]=tot;//插入表头
}
//默认head[]为0,作为空指针在循环中会被终止
void dfs(int x){
vis[x]=true;
dfsline[++time]=x;
in[x] = time;
for(int i=head[x];i;i=next[i]){
int y=ver[i];
if(!vis[y]) dfs(y);
}
out[x]=time;
}
int lowbit(int x) {
return x & -x;
}
void put(int pos,int value){
for(int i=pos;i<=SIZE;i+=lowbit(i)){
Tree[i]+=value;
}
}
int sum(int x){
int ans=0;
for(int i=x;i;i-=lowbit(i)) ans+=Tree[i];
return ans;
}
int main(){
int n,x,y;
scanf("%d",&n);
fore(i,1,n-1){
scanf("%d%d",&x,&y);
add(x,y,1);
}
dfs(1);
fore(i,1,time){
put(dfsline[i],1);
fork[i]=1;
}
scanf("%d",&n);
char c;
fore(i,1,n){
std::cin>>c;
scanf("%d",&x);
if(c=='Q'){
int ans=0;
ans=sum(out[x])-sum(in[x]-1);
printf("%d\n",ans);
}
else{
if(fork[x]) put(in[x],-1);
else put(in[x],1);
fork[x]=!fork[x];
}
}
return 0;
}
标签:fork,kaka,apple,tree,dfs,求子,poj3321,forks,apples 来源: https://www.cnblogs.com/rign/p/10464926.html