树剖会T?
查看原帖
树剖会T?
554803
After_light楼主2023/3/19 08:27
#include<bits/stdc++.h>
#define ll long long
#define F(i,a,b) for(ll i=a;i<=b;i++)
#define R(i,a,b) for(ll i=a;i>=b;i--)
#define sc(a) scanf("%lld",&a)
#define ps(a) printf("%lld ",a)
#define pn(a) printf("%lld\n",a)
using namespace std;
const ll N=3e6+7;
ll n,q,s,son[N],dep[N],fa[N],top[N];
struct edge{
	ll nxt,to;
	edge(ll _nxt=0,ll _to=0){
		nxt=_nxt,to=_to;
	}
}e[N];
ll head[N],cnt;
inline void add_edge(ll from,ll to){
	e[++cnt]=edge(head[from],to);
	head[from]=cnt;
}
inline ll dfs1(ll now,ll f){
	fa[now]=f;
	ll maxn=0,so=0;
	dep[now]=dep[f]+1;
	ll sz=1;
	if(!head[now]) return sz;
	for(ll i=head[now];i;i=e[i].nxt){
		if(e[i].to==f) continue;
		ll x=dfs1(e[i].to,now);
		sz+=x;
		if(x>maxn){
			maxn=e[i].to,so=e[i].to;
		}
	}
	son[now]=so;
	return sz;
}
inline void dfs2(ll now,ll t){
	top[now]=t;
	if(!son[now]){
		return ;
	}
	dfs2(son[now],t);
	for(ll i=head[now];i;i=e[i].nxt){
		if(e[i].to==fa[now]||e[i].to==son[now]) continue;
		dfs2(e[i].to,e[i].to);
	}
}
inline ll query(ll x,ll y){
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]]) swap(x,y);
		x=fa[top[x]];
	}
	if(dep[x]<dep[y]) return x;
	return y;
}
int main(){
	sc(n),sc(q),sc(s);
	F(i,1,n-1){
		ll from,to;
		sc(from),sc(to);
		add_edge(from,to);
		add_edge(to,from);
	}
	dfs1(s,0);
	dfs2(s,s);
	F(i,1,q){
		ll x,y;
		sc(x),sc(y);
		pn(query(x,y));
	}
	return 0;
}
2023/3/19 08:27
加载中...