树剖 10pts 求条
查看原帖
树剖 10pts 求条
920406
违规用户名920406楼主2024/12/16 20:53
#include <iostream>
#include <vector>
using namespace std;
const int N=5e5+1;
int n,m,r,f,t,x,y,tim,fa[N],dep[N],siz[N],hson[N],belong[N];
vector<int> son[N];
void dfs(int i,int f)
{
    fa[i]=f;
    siz[i]=1;
    dep[i]=dep[f]+1;
    for(auto x:son[i])
        if(x!=f)
        {
            dfs(x,i);
            siz[i]+=siz[x];
            if(siz[hson[i]]<siz[x]) hson[i]=x;
        }
}
void dfs2(int i,int op)
{
    if(op)  belong[i]=i;
    else    belong[i]=belong[fa[i]];
    if(hson[i]) dfs2(hson[i],1);
    for(auto x:son[i])
        if(x!=fa[i]&&x!=hson[i])
            dfs2(x,0);
}
int lca(int x,int y)
{
    while(belong[x]!=belong[y])
    {
        if(dep[x]<dep[y])   swap(x,y);
        x=fa[belong[x]];
    }
    if(dep[x]<dep[y])   return x;
    return y;
}
int main()
{
    cin>>n>>m>>r;
    for(int i=1;i<n;i++)
    {
        cin>>f>>t;
        son[f].push_back(t);
        son[t].push_back(f);
    }
    dfs(r,0);
    dfs2(r,1);
    while(m--)
    {
        cin>>x>>y;
        cout<<lca(x,y)<<endl;
    }
    return 0;
}
2024/12/16 20:53
加载中...