萌新刚学LCA, 倍增 #2 #9 #10 TLE 求助
查看原帖
萌新刚学LCA, 倍增 #2 #9 #10 TLE 求助
243024
gdjcwsk楼主2020/4/30 21:08

rt

#include <bits/stdc++.h>
using namespace std;
const int maxn=1000005;
int nn,heads[maxn],l2[maxn],parent[maxn][20],depth[maxn];
struct node
{
    int to,next;
}pool[2*maxn];
void dfs(int r,int father)
{
    depth[r]=depth[father]+1;
    parent[r][0]=father;
    for(int i=1;(1<<i)<=depth[r];i++)
    {
        parent[r][i]=parent[parent[r][i-1]][i-1];
    }
    for(int i=heads[r];i!=0;i=pool[i].next)
    {
        if(pool[i].to!=father)
        {
            dfs(pool[i].to,r);
        }
    }
}
int lca(int x,int y)
{
    if(depth[x]<depth[y])
    {
        swap(x,y);
    }
    while(depth[x]>depth[y])
    {
        x=parent[x][l2[depth[x]-depth[y]]-1];
    }
    if(x==y)
    {
        return x;
    }
    for(int i=l2[depth[x]]-1;i>=0;i--)
    {
        if(parent[x][i]!=parent[y][i])
        {
            x=parent[x][i];
            y=parent[y][i];
        }
    }
    return parent[x][0];
}
void addedge(int u,int v)
{
    pool[++nn].to=v;
    pool[nn].next=heads[u];
    heads[u]=nn;
}
int main()
{
    int n,m,s;
    cin>>n>>m>>s;
    for(int i=1;i<=n-1;i++)
    {
        int a,b;
        cin>>a>>b;
        addedge(a,b);
        addedge(b,a);
    }
    for(int i=1;i<=n;i++)
    {
        l2[i]=l2[i-1]+((1<<l2[i-1])==i);
    }
    dfs(s,0);
    for(int i=0;i<m;i++)
    {
        int x,y;
        cin>>x>>y;
        cout<<lca(x,y)<<endl;
    }
}
2020/4/30 21:08
加载中...