模板 - 图论 - 最近公共祖先 - 倍增算法 - LCA

lixiaotao 2020-02-16

const int MAX = 100000;
vector <int> G[MAXN + 5];
int dep[MAXN + 5], fa[MAXN + 5][20 + 1];

void dfs(int u, int p) {
    dep[u] = depth[p] + 1;
    fa[u][0] = p;
    for (int i = 1; i <= 20; i++)
        fa[u][i] = fa[fa[u][i - 1]][i - 1];
    for(auto &v : G[u]) {
        if(v == p)
            continue;
        dfs(v, u);
    }
}

int LCA(int x, int y) {
    if (dep[x] < dep[y])
        swap(x, y);
    for (int i = 20; i >= 0; i--)
        if (dep[x] - (1 << i) >= dep[y])
            x = fa[x][i];
    if (x == y)
        return x;
    for (int i = 20; i >= 0; i--)
        if (fa[x][i] != fa[y][i])
            x = fa[x][i], y = fa[y][i];
    return fa[x][0];
}

相关推荐