码迷,mamicode.com
首页 > 其他好文 > 详细

LCA 模板

时间:2017-09-05 10:49:36      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:char   ++   blog   can   span   main   return   ==   color   

#include <bits/stdc++.h>

using namespace std;

#define REP(i,n)                for(int i(0); i <  (n); ++i)
#define rep(i,a,b)              for(int i(a); i <= (b); ++i)
#define dec(i,a,b)              for(int i(a); i >= (b); --i)
#define for_edge(i,x)           for(int i = H[x]; i; i = X[i])

const int N     =    100000      +       10;
const int M     =    10000       +       10;
const int Q     =    1000        +       10;
const int A     =    30          +       1;

int T;
int n, m;
int x, y, z;

int E[N << 1], X[N << 1], H[N << 1];
int deep[N];
int f[N][A];
int et;

inline void addedge(int a, int b){
    E[++et] = b, X[et] = H[a], H[a] = et;
    E[++et] = a, X[et] = H[b], H[b] = et;
}

void dfs(int x, int fa, int dep){
    deep[x] = dep;
    if (fa){
        f[x][0] = fa;
        for (int i = 0; f[f[x][i]][i]; ++i)
            f[x][i + 1] = f[f[x][i]][i];
    }

    for_edge(i, x) if (E[i] != fa){
        dfs(E[i], x, dep + 1);
    }
}

int LCA(int a, int b){
    if (deep[a] < deep[b]) swap(a, b);
    for (int i = 0,  delta = deep[a] - deep[b]; delta; delta >>= 1, ++i)
        if (delta & 1) a = f[a][i];

    if (a == b) return a;
    dec(i, 19, 0) if (f[a][i] != f[b][i]){
        a = f[a][i];
        b = f[b][i];
    }

    return f[a][0];
}

int main(){

    scanf("%d", &T);
    while (T--){
        et = 0;
        memset(H, 0, sizeof H);
        scanf("%d%d", &n, &m);
        rep(i, 1, n - 1){
            scanf("%d%d", &x, &y);
            addedge(x, y);
        }
        rep(i, 1, m){
            scanf("%d%d%d", &x, &y, &z);
        }
        dfs(1, 0, 0);
        rep(i, 1, n){
            for (int j = 0; f[i][j]; ++j) printf("%d ", f[i][j]);
            putchar(10);
        }

        rep(i, 1, n) printf("%d ", deep[i]);  putchar(10);

        printf("%d\n", LCA(4, 6));
        printf("%d\n", LCA(2, 3));
        printf("%d\n", LCA(4, 5));
    }

    return 0;

}

来自cxhscst2,<( ̄︶ ̄)>

LCA 模板

标签:char   ++   blog   can   span   main   return   ==   color   

原文地址:http://www.cnblogs.com/stepping/p/7477372.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!