原题链接:https://www.luogu.org/problemnew/show/P4116
Qtree3
题目描述
给出N个点的一棵树(N-1条边),节点有白有黑,初始全为白
有两种操作:
0 i : 改变某点的颜色(原来是黑的变白,原来是白的变黑)
1 v : 询问1到v的路径上的第一个黑点,若无,输出-1
输入输出格式
输入格式:
第一行 N,Q,表示N个点和Q个操作
第二行到第N行N-1条无向边
再之后Q行,每行一个操作"0 i" 或者"1 v" (1 ≤ i, v ≤ N).
输出格式:
对每个1 v操作输出结果
输入输出样例
输入样例#1:
9 8
1 2
1 3
2 4
2 9
5 9
7 9
8 9
6 8
1 3
0 8
1 6
1 7
0 2
1 9
0 2
1 9
输出样例#1:
-1
8
-1
2
-1
说明
For 1/3 of the test cases, N=5000, Q=400000.
For 1/3 of the test cases, N=10000, Q=300000.
For 1/3 of the test cases, N=100000, Q=100000.
题解
因为要询问深度,所以我们定义一棵有根的 L C T \mathcal{LCT} LCT,然后维护一下以每个节点为根的 S p l a y Splay Splay中深度最浅的黑点的编号就好了。
代码
#include<bits/stdc++.h>
#define ls son[v][0]
#define rs son[v][1]
using namespace std;
const int M=1e5+5;
int n,q,dad[M],son[M][2],bla[M],dep[M],fa[M];
bool col[M];
vector<int>mmp[M];
bool notroot(int v){return son[dad[v]][0]==v||son[dad[v]][1]==v;}
void up(int v)
{
bla[v]=dep[bla[ls]]<dep[bla[rs]]?bla[ls]:bla[rs];
if(col[v])bla[v]=dep[bla[v]]<dep[v]?bla[v]:v;
}
void spin(int v)
{
int f=dad[v],ff=dad[f],k=son[f][1]==v,w=son[v][!k];
if(notroot(f))son[ff][son[ff][1]==f]=v;son[v][!k]=f,son[f][k]=w;
if(w)dad[w]=f;dad[f]=v,dad[v]=ff;up(f);
}
void splay(int v)
{
int f,ff;
while(notroot(v))
{
f=dad[v],ff=dad[f];
if(notroot(f))spin((son[f][0]==v)^(son[ff][0]==f)?v:f);
spin(v);
}
up(v);
}
void access(int v){for(int f=0;v;v=dad[f=v])splay(v),rs=f,up(v);}
void link(int v){splay(v);int f=dad[v]=fa[v];access(f);splay(f);son[f][1]=v;up(f);}
void in()
{
int a,b;
scanf("%d%d",&n,&q);
for(int i=1;i<n;++i){scanf("%d%d",&a,&b),mmp[a].push_back(b),mmp[b].push_back(a);}
}
void dfs(int v,int f,int d)
{
fa[v]=f;dep[v]=d;int to;
for(int i=mmp[v].size()-1;i>=0;--i)
{
to=mmp[v][i];if(to==f)continue;
dfs(to,v,d+1);
}
link(v);
}
void ac()
{
int op,v;dep[0]=INT_MAX;
dfs(1,n+1,1);
for(int i=1;i<=q;++i)
{
scanf("%d%d",&op,&v);
if(op){access(1);splay(1);access(v);if(bla[1])printf("%d\n",bla[1]);else puts("-1");}
else splay(v),col[v]^=1,up(v);
}
}
int main(){in();ac();}