zoukankan      html  css  js  c++  java
  • P3379【模板】最近公共祖先

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn=5e5+100;
    int n,m,s;
    int father[20][maxn];
    vector<int> g[maxn];
    int h[maxn];
    void dfs (int x) {
        for (int i=0;i<g[x].size();i++) {
            int v=g[x][i];
            if (v==father[0][x]) continue;
            father[0][v]=x;
            h[v]=h[x]+1;
            dfs(v);
        }
    }
    int lca (int x,int y) {
        if (h[x]<h[y]) swap(x,y);
        for (int i=17;i>=0;i--)
            if (h[x]-h[y]>>i) x=father[i][x];
        if (x==y) return x;
        for (int i=17;i>=0;i--) 
            if (father[i][x]!=father[i][y]) {
                x=father[i][x];
                y=father[i][y];
            }
        return father[0][x];
    }
    int main () {
        scanf("%d%d%d",&n,&m,&s);
        for (int i=1;i<n;i++) {
            int x,y;
            scanf("%d%d",&x,&y);
            g[x].push_back(y);
            g[y].push_back(x);
        }
        dfs(s);
        for (int i=1;i<=17;i++)
            for (int j=1;j<=n;j++)
                father[i][j]=father[i-1][father[i-1][j]];
        for (int i=0;i<m;i++) {
            int x,y;
            scanf("%d%d",&x,&y);
            printf("%d
    ",lca(x,y));
        }
    }
  • 相关阅读:
    code3728 联合权值
    Codevs 4600 [NOI2015]程序自动分析
    code1540 银河英雄传说
    code1074 食物链
    堆排序
    哈夫曼树与哈夫曼码
    优先队列用法
    code1154 能量项链
    code1225 八数码Bfs
    javascript5
  • 原文地址:https://www.cnblogs.com/zhanglichen/p/13448529.html
Copyright © 2011-2022 走看看