求调树剖
查看原帖
求调树剖
776799
GODTREE楼主2024/3/17 11:31
#include <bits/stdc++.h>
#define N 5000005
using namespace std;
int n,m,r;
struct node
{
	int f,sz,d,top;
	vector<int> s;
}t[N];
bool cmp(int x,int y)
{
	return t[x].sz>t[y].sz;
}
void dfs_1(int u,int deep)
{
	t[u].d=deep;
	t[u].sz=1;
	for (int i=0;i<t[u].s.size();i++)
	{	
		dfs_1(t[u].s[i],deep+1);
		t[u].sz+=t[t[u].s[i]].sz;
	}
	sort(t[u].s.begin(),t[u].s.end(),cmp);
}
void dfs_2(int u,int _top)
{
	t[u].top=_top;
	if (t[u].s.size()==0)
	{
		return ;
	}
	dfs_2(t[u].s[0],_top);
	for (int i=1;i<t[u].s.size();i++)
	{
		dfs_2(t[u].s[i],t[u].s[i]);
	}
	return ;
}
int lca(int a, int b)
{
    while (t[a].top != t[b].top)
    {
        if (t[a].top==a) return a;
        if (t[b].top==b) return b;
        if (t[a].d<t[b].d) swap(a, b);
        a = t[t[a].top].f;
    }
    return t[a].d<t[b].d?a:b;
}
int main()
{
	cin>>n>>m>>r;
	for (int i=1;i<n;i++)
	{
		int x,y;
		cin>>x>>y;
		if (y!=r) t[x].s.push_back(y),t[y].f=x;
		else t[y].s.push_back(x),t[x].f=y;
	}
	dfs_1(r,0);
	dfs_2(r,r);
	for (int i=1;i<=m;i++)
	{
		int a,b;
		cin>>a>>b;
		cout<<lca(a,b)<<"\n";
	}
	return 0;
}
2024/3/17 11:31
加载中...