• 模板_LCA


    // luogu-judger-enable-o2
    #include<bits/stdc++.h>
    #define maxn 1000002
    //#define int long long
    //#define kcz
    using namespace std;
    inline int read()
    {
        char x = getchar();
        int lin = 0,f = 1;
        while(x < '0' || x > '9')
        {
            if(x == '-') f = -1;
            x = getchar();
        }
        while(x >= '0' && x <= '9')
        {
            lin = (lin << 1) + (lin << 3) + x - '0';
            x = getchar();
        }
        return lin * f;
    }
    #define PII pair<int,int>
    #define fir first
    #define sec second
    #define ma(a,b) make_pair(a,b)
    #define inf 123123123
    int head[maxn],u,v,tot,n,m,dep[maxn],q,fa[maxn][23],rt;
    struct st{
        int v,nex;
    }s[maxn];
    void add(int u,int v)
    {
        s[++tot] = (st) { v,head[u] };
        head[u] = tot;
    }
    void dfs(int now,int F)
    {
        fa[now][0] = F;dep[now]=dep[F]+1;
        for(int i=1;i<=22;i++)fa[now][i]=fa[fa[now][i-1]][i-1];
        for(int i = head[now]; i; i = s[i].nex)
            if(s[i].v != F)
            {
                dfs(s[i].v,now);
            }
    }
    int lca(int a,int b)
    {
        if(dep[a] > dep[b]) swap(a,b);
        int len = dep[b] - dep[a];
        for(int i = 0; (1 << i) <= len; i++)
            if(len & (1 << i))
                b = fa[b][i];
        if(a != b)
        {
            for(int i = 22; i >= 0; i--)
            {
                if(fa[a][i] != fa[b][i])
                {
                    a = fa[a][i];
                    b = fa[a][i];
                }
            }
            a = fa[a][0];
        }
        return a;
    }
    signed main(){
        n = read(); q = read(); rt = read();
        for(int i = 1; i < n; i++)
        {
            u = read(); v = read();
            add(u,v); add(v,u);
        }
        dfs(rt,0);
        for(int i = 1; i <= q; i++)
        {
            u = read(); v = read();
            printf("%d
    ",lca(u,v));
        }
    }
  • 相关阅读:
    3. VIM 系列
    2. VIM 系列
    2. 修复FFMPEG 复用 PAT、PMT发送间隔小于25ms的错误
    1. VIM 系列
    RESTful风格API
    APIview的使用
    1.DRF初始化
    Linux下的django项目02
    Linux下的django项目01
    1,web项目工作流程
  • 原文地址:https://www.cnblogs.com/kczno1fans/p/9922252.html
Copyright © 2020-2023  润新知