【dfs序】【线段树】【树状数组】苹果树

【题目描述】  

here 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?20170801235223_17885

给出一个苹果树,每个节点一开始都有苹果

C X,如果X点有苹果,则拿掉,如果没有,则新长出一个

Q X,查询X点与它的所有后代分支一共有几个苹果

【输入】

第一行是节点总数N (N ≤ 100,000) ,

接下来N-1行表示N-1条边 根节点为1

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

【输出】

For every inquiry, output the correspond answer per line

【样例输入】

3
1 2
1 3
3
Q 1
C 2
Q 1

【样例输出】

3
2

分析:

题意:对于一棵树,支持:单点修改(对某个点x加上一个权值w),子树查询(查询子树x内所有点的权值和)

解:列出dfs序,由dfs序性质(一棵子树所有节点在dfs序里是连续的一段)可将原题转化为:

        在dfs序中单点修改,区间求和,树状数组/线段树即可。

代码:

这里楼主使用的是更快更简洁的树状数组
#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) x&(-x)
inline int read(){
	int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
   	return x*f;
}
const int N=1e5+10;
int T[N],n,m,first[N],cnt,st[N],ed[N],dfn[N],tot,q[N];
struct node{
	int v,nxt;
}e[N*2];
inline int add(int u,int v){
	e[++cnt].v=v;
	e[cnt].nxt=first[u];
	first[u]=cnt;
}
inline void update(int x,int v){
	while(x<=n){
		T[x]+=v;
		x+=lowbit(x);
	}  
}
inline int query(int x){
	int sum=0;
	while(x>0){
		sum+=T[x];
		x-=lowbit(x);
	}
	return sum;
}
inline void dfs(int x){
	st[x]=++tot;
	for(int i=first[x];i;i=e[i].nxt){
		int v=e[i].v;
		if(!st[v]) dfs(v); 
	} 
	ed[x]=tot;
}
int main(){
	n=read();
	for(int i=1;i<n;++i){
		int u=read(),v=read();
		add(u,v);
		add(v,u);
	}
	
	dfs(1);
	m=read();
	for(int i=1;i<=n;++i) update(st[i],1),q[i]=1;
	while(m--){
		char op=getchar();
		while(op!='C'&&op!='Q') op=getchar();
		if(op=='C'){
			int x=read();
			if(q[x])
				update(st[x],-1);
			else update(st[x],1);
			q[x]^=1;
		}
		if(op=='Q'){
			int x=read();
			printf("%d\n",query(ed[x])-query(st[x]-1)); 
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42754826/article/details/88916668