对于多次操作的树上题目,都最好考虑下以下个人发现的一个思路.
1.考虑在数组(一条链)上怎么实现,
2.考虑把数组的情况扩展到树上.
对于方法2,常常会用到树上差分,树链剖分等技巧
对于本题,可以考虑维护一条链上最早出现的那个黑点(深度最浅),
使用树链剖分实现,线段树维护两个值
<
x
,
y
>
<x,y>
<x,y>,表示这一个区间最浅的黑点是
x
,
深度为
y
x,深度为y
x,深度为y.
这代码确实太长了,有一个地方写错都得查找很久
/*
You held me down but I broke free,
I found the love inside of me.
Now I don't need a hero to survive
Cause I already saved my life.
*/
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+5;
const int INF = 1e9+7;
typedef long long ll;
typedef pair<int,int> pii;
#define all(a) (a).begin(), (a).end()
#define pb(a) push_back(a)
vector<int> G[maxn];
#define L (idx<<1)
#define R (idx<<1|1)
#define MID (start+end>>1)
struct Node{
int x,y;//<depth,id>
}tree[maxn*4+5];
void push_up(int idx){
if(tree[L].x<tree[R].x) tree[idx] = tree[L];
else tree[idx] = tree[R];
}
void build(int idx,int start,int end){
if(start==end){
tree[idx].x = INF;
tree[idx].y = -1;
return ;
}
build(L,start,MID);build(R,MID+1,end);
push_up(idx);
}
void update(int idx,int start,int end,int pos,int d,int k){
if(start==end&&start==pos){
if(tree[idx].x==INF) tree[idx].x = d;
else tree[idx].x = INF;
tree[idx].y = k;
return ;
}
if(pos>=start&&pos<=MID) update(L,start,MID,pos,d,k);
if(pos>=MID+1&&pos<=end) update(R,MID+1,end,pos,d,k);
push_up(idx);
}
Node query(int idx,int start,int end,int l,int r){
if(start>=l&&end<=r) return tree[idx];
Node ans = {INF,-1};
if(l<=MID) ans = query(L,start,MID,l,r);
if(r>MID){
Node tp = query(R,MID+1,end,l,r);
if(tp.x<ans.x) ans = tp;
}
return ans;
}
int son[maxn],fa[maxn],depth[maxn],top[maxn],dfs_clock=0,sz[maxn],id[maxn];
int n;
void dfs1(int u,int f){
depth[u] = depth[f]+1;fa[u] = f;sz[u]=1;
for(auto v : G[u]){
if(v==f) continue;
dfs1(v,u);sz[u]+=sz[v];
if(son[u]==0||sz[son[u]]<sz[v]) son[u] = v;
}
}
void dfs2(int u,int topf){
id[u]=++dfs_clock;top[u] = topf;
if(son[u]) dfs2(son[u],topf);
for(auto v : G[u]){
if(v==fa[u]||v==son[u]) continue;
dfs2(v,v);
}
}
int tr_query(int x,int y){
Node ans = {INF,-1};
while(top[x]!=top[y]){
if(depth[top[x]]<depth[top[y]]) swap(x,y);
Node tp = query(1,1,n,id[top[x]],id[x]);
if(tp.x<ans.x) ans = tp;
x = fa[top[x]];
}
if(depth[x]>depth[y]) swap(x,y);
Node tp = query(1,1,n,id[x],id[y]);
if(tp.x<ans.x) ans = tp;
return ans.y;
}
void tr_update(int x){
update(1,1,n,id[x],depth[x],x);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int Q;
cin>>n>>Q;
for(int i=1;i<=n-1;i++){
int u,v;cin>>u>>v;
G[u].pb(v);G[v].pb(u);
}
dfs1(1,0);
dfs2(1,1);
build(1,1,n);
while(Q--){
int op;cin>>op;
if(op==0){
int x;cin>>x;
tr_update(x);
}
else{
int x;cin>>x;
cout<<tr_query(1,x)<<"\n";
}
}
}