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));
        }
    }
  • 相关阅读:
    JS 面向对象
    堆 栈
    考试题
    HTML Meta标签
    Nodejs 安装
    CSS3 背景图片的大小位置
    JS Math函数
    CSS3 巧用before after选择器
    计算机网络原理_数据链路层
    Asp.net_验证控件
  • 原文地址:https://www.cnblogs.com/zhanglichen/p/13448529.html
Copyright © 2011-2022 走看看