1. 程式人生 > 實用技巧 >求最近公共祖先LCA兩種方法

求最近公共祖先LCA兩種方法

tarjan求lca

  • 這種演算法本質上是用並查集對向上標記法的優化,是離線演算法,即一次性讀入所有詢問,統一計算,統一輸出。
    時間複雜度\(O(n+m)\)

    • v[]進行標記
      \(v[x]\doteq 0\) --> x節點未訪問過
      \(v[x]\doteq 1\) --> x節點已經訪問,但未回溯
      \(v[x]\doteq 2\) --> x節點已經訪問並回溯
  • code

    #include <cstdio>
    #include <vector>
    #include <algorithm>
    using namespace std;
    const int N = 1e5+5;
    struct side {
        int t, d, next;
    }e[N<<1];
    int head[N], tot;
    void add(int x, int y, int z) {
        e[++tot].next = head[x];
        head[x] = tot;
        e[tot].t = y, e[tot].d = z;
    }
    int n, m, Q, d[N], f[N], v[N], ans[N];
    vector<int> q[N], h[N];
    int found(int x) {
        return x == f[x] ? x : (f[x] = found(f[x]));
    }
    void tarjan(int x) {
        v[x] = 1;
        for (int i = head[x]; i; i = e[i].next) {
            int y = e[i].t;
            if (v[y]) continue;
            d[y] = d[x] + e[i].d;
            tarjan(y);
            f[y] = x;
        }
        for (int i = 0; i < q[x].size(); i++) {
            int y = q[x][i], id = h[x][i];
            if (v[y] != 2) continue;
            ans[id] = min(ans[id], d[x] + d[y] - 2*d[found(y)]);
        }
        v[x] = 2;
    }
    int main() {
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= n; i++) f[i] = i;
        while (m--) {
            int x, y, z;
            scanf("%d%d%d", &x, &y, &z);
            add(x, y, z); add(y, x, z);
        }
        scanf("%d", &Q);
        for (int i = 1; i <= Q; i++) {
            int x, y;
            scanf("%d%d", &x, &y);
            if (x == y) continue;
            ans[i] = 1 << 30;
            q[x].push_back(y), h[x].push_back(i);
            q[y].push_back(x), h[y].push_back(i);
        }
        tarjan(1);
        for (int i = 1; i <= Q; i++)
            printf("%d\n", ans[i]);
        return 0;
    }
    

倍增求Lca

  • f[x][k]表示從x向根節點走\(2^k\)步到達的節點
    d[x]表示樹的深度
    預處理時間複雜度為\(O(n\log n)\),每次詢問時間複雜度為\(O(\log n)\)

    • code
      int d[N], f[N][21];
      void dfs(int x, int fa) {
          f[x][0] = fa;
          d[x] = d[fa] + 1;
          for (int i = 1; i <= 20; i++)
              f[x][i] = f[f[x][i-1]][i-1];
          for (int i = head[x]; i; i = e[i].next) 
              if (e[i].t != fa) dfs(e[i].t, x);
      }
      int lca(int x, int y) {
          if (d[x] > d[y]) swap(x, y);
          y = found(y, d[y] - d[x]);
          if (x == y) return x;
          for (int i = 20; i >= 0; i--)
              if (f[x][i] != f[y][i])
                  x = f[x][i], y = f[y][i];
          return f[x][0];
      }