Lca

最近公共祖先

\((1)向上标记法\ O(n)\)

\((2)倍增:fa[i,j]表示从i开始,向上走2^j步所能走到的节点,0 \le j\le log_2n,depth[i]表示深度\)

\(步骤\)

  • \(先将两个点跳到同一层\)
  • \(让两个点同时往上跳,一直跳到它们的最近公共祖先的下一层\)
  • \(预处理\ O(nlogn)\)
  • \(查询\ O(logn)\)

\(下面是一道裸题:\)祖先询问

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 40010, M = N * 2;
int n, m;
int h[N], e[M], w[M], ne[M], idx;
int depth[N], fa[N][16];
int q[N];

void add(int a, int b) {
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void bfs(int root) {
    memset(depth, 0x3f, sizeof depth);
    depth[0] = 0, depth[root] = 1;//哨兵
    int hh = 0, tt = 0;
    q[0] = root;
    while (hh <= tt) {
        int t = q[hh++];
        for (int i = h[t]; ~i; i = ne[i]) {
            int j = e[i];
            if (depth[j] > depth[t] + 1) {
                depth[j] = depth[t] + 1;
                q[++tt] = j;
                fa[j][0] = t;
                for (int k = 1; k <= 15; ++k) 
                    fa[j][k] = fa[fa[j][k - 1]][k - 1]; // 这里体现了倍增
            }
        }
    }
}

int lca(int a, int b) {
    if (depth[a] < depth[b]) swap(a, b);
    for (int k = 15; k >= 0; --k) // 做完这一步循环保证depth[a] >= depth[b]
        if (depth[fa[a][k]] >= depth[b])  
            a = fa[a][k];
    if (a == b) return a;
    for (int k = 15; k >= 0; --k) // depth[a] 时刻保证 >= depth[b]
        if (fa[a][k] != fa[b][k]) {
            a = fa[a][k];
            b = fa[b][k];
        }
    return fa[a][0];
}

int main() {
    IO;
    int n;
    cin >> n;
    int root = 0;
    memset(h, -1, sizeof h);
    for (int i = 0; i < n; ++i) {
        int a, b;
        cin >> a >> b;
        if (b == -1) root = a;
        else add(a, b), add(b, a);
    }
    bfs(root);
    cin >> m;
    while (m--) {
        int a, b;
        cin >> a >> b;
        int p = lca(a, b);
        if (p == a) puts("1");
        else if (p == b) puts("2");
        else puts("0");
    }
    return 0;
}
posted @ 2021-02-18 14:12  phr2000  阅读(67)  评论(0编辑  收藏  举报