Jzoj4604 树

子树的问题都是dfs序的工作啦,加上个线段树就ok了

#include<stdio.h>
#define mid (l+r>>1)
struct Edge{ int v,nt; } G[200010];
int h[100010],cnt=0,clk=0,l[100010],r[100010];
int s[400040],n,m,d[100010]; char c[5];
void adj(int x,int y){ G[++cnt]=(Edge){y,h[x]}; h[x]=cnt; }
void dfs(int x,int f){
	l[x]=++clk; d[x]=d[f]+1;
	for(int v,i=h[x];i;i=G[i].nt)
		if((v=G[i].v)!=f) dfs(v,x);
	r[x]=clk;
}
int query(int l,int r,int x,int p){
	if(s[x]) return s[x];
	if(p<=mid) return query(l,mid,x<<1,p);
	else return query(mid+1,r,x<<1|1,p);
}
void update(int l,int r,int x,int L,int R,int k){
	if(L<=l && r<=R && s[x]){ if(d[s[x]]<d[k]) s[x]=k; return; }
	if(s[x]) s[x<<1]=s[x<<1|1]=s[x]; s[x]=0;
	int m=mid;
	if(L<=m) update(l,m,x<<1,L,R,k);
	if(m<R) update(m+1,r,x<<1|1,L,R,k);
}
int main(){
	scanf("%d%d",&n,&m); s[1]=1;
	for(int x,y,i=1;i<n;++i){
		scanf("%d%d",&x,&y);
		adj(x,y); adj(y,x);
	}
	dfs(1,0);
	for(int x,i=0;i<m;++i){
		scanf("%s%d",c,&x);
		if(*c=='Q') printf("%d
",query(1,n,1,l[x]));
		else update(1,n,1,l[x],r[x],x);
	}
}

原文地址:https://www.cnblogs.com/Extended-Ash/p/7774377.html