首页 > 代码库 > 倍增求LCA

倍增求LCA

LCA:(Least Common Ancestors),即最近公共祖先节点。

 1 const int maxn = 100003;
 2 const int maxl = 19;
 3 
 4 struct Edge {
 5     int t;
 6     Edge *ne;
 7 };
 8 
 9 int dep[maxn], up[maxn][maxl];
10 Edge *head[maxn];
11 
12 void DFS(int u) {
13     for (int i = 1; i < maxl; ++ i) {
14         up[u][i] = up[up[u][i - 1]][i - 1];
15     }
16     for (Edge* e = head[u]; e; e = e->ne) { // 枚举儿子
17         if (!dep[e->t]) {
18             dep[e->t] = dep[u] + 1;
19             up[e->t][0] = u;
20             DFS(e->t);
21         }
22     }
23 }
24 
25 int LCA(int u, int v) {
26     if (dep[u] < dep[v]) {
27         swap(u, v);
28     }
29     for (int i = maxl - 1; i >= 0; -- i) {
30         if (dep[up[u][i]] >= dep[v]) {
31             u = up[u][i];
32         }
33     }//保证深度相同 
34     if (u == v) {
35         return u;
36     }
37     for (int i = maxl - 1; i >= 0; -- i) {
38         if (up[u][i] != up[v][i]) {
39             u = up[u][i];
40             v = up[v][i];
41         }
42     }
43     return up[u][0];
44 }
45 
46 int main() {
47     memset(dep, -1, sizeof(dep));
48     dep[1] = 0;
49     up[1][0] = 0;
50     DFS(1);
51     while (q --) {
52         int u, v;
53         cin >> u >> v;
54         cout << LCA(u, v) << endl;
55     }
56 }

 

倍增求LCA