比赛 20240913练习 评测结果 AAAAA
题目名称 白黑树 最终得分 100
用户昵称 ┭┮﹏┭┮ 运行时间 0.691 s
代码语言 C++ 内存使用 19.54 MiB
提交时间 2024-09-13 20:16:43
显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define fi first
#define in inline
#define se second
#define mp make_pair
#define pb push_back
const int N = 3e5+10;

ll read(){
	ll x = 0,f = 1;char c = getchar();
	for(;c < '0' || c > '9';c = getchar())if(c == '-')f = -1;
	for(;c >= '0' && c <= '9';c = getchar())x = (x<<1) + (x<<3) + c-'0';
	return x * f;
}


int n,m;
bool v[N];

struct BIT{
	int c[N];
	int lowbit(int x){return x & (-x);}
	void add(int x,int val){
		for(;x <= n;x += lowbit(x))c[x] += val;
	}
	int ask(int x){
		int ans = 0;
		for(;x > 0;x -= lowbit(x))ans += c[x];
		return ans;
	}
	int ask(int l,int r){return ask(r) - ask(l-1);}
}t;


vector<int>e[N];
struct Tree{
	int dfn[N],siz[N],anc[N][22],cnt;
	void dfs(int x){
		for(int i = 1;i <= 20;i++)anc[x][i] = anc[anc[x][i-1]][i-1];
		dfn[x] = ++cnt,siz[x] = 1;
		for(int y : e[x]){
			if(y == anc[x][0])continue;
			anc[y][0] = x;
			dfs(y),siz[x] += siz[y];
		}
	}
	int ask(int x,int k){
		for(int i = 20;i >= 0;i--){
			int y = anc[x][i];
			int s = t.ask(dfn[y],dfn[y] + siz[y] - 1);
			if(s < k)x = y;
		}
		int s = t.ask(dfn[x],dfn[x] + siz[x] - 1);
		if(s < k)x = anc[x][0];
		return x;
	}
	void build(){
		for(int i = 0;i <= 20;i++)anc[1][i] = 1;
		dfs(1);
	}
}T;


int sum;
int main(){
	freopen("C_Tree.in","r",stdin);
	freopen("C_Tree.out","w",stdout);
	n = read(),m = read();
	for(int i = 1;i < n;i++){
		int x = read(),y = read();
		e[x].pb(y),e[y].pb(x);
	}
	T.build();
	for(int i = 1;i <= n;i++){
		char c;cin>>c;
		int x = read();
		if(c == 'M'){
			sum += v[x] ? -1 : 1;
			t.add(T.dfn[x],v[x] ? -1 : 1);
			v[x] = !v[x];
		}
		else{
			if(!sum)printf("-1\n");
			else printf("%d\n",T.ask(x,sum));
		}
	}

	return 0;

}