LCA

旧时模样 提交于 2019-11-28 03:57:38
 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cstring>
 5 using namespace std;
 6 const int maxn = 1e6 + 5;
 7 struct node
 8 {
 9     int u , v , next;    
10 }G[maxn];
11 int tail , head[maxn];
12 int n , m , s;
13 int depth[maxn] , father[maxn][25] , lg[maxn];
14 void add(int u , int v)
15 {
16     tail++;
17     G[tail].u = u , G[tail].v = v , G[tail].next = head[u];
18     head[u] = tail;
19 }
20 void dfs(int p , int fa)
21 {
22     depth[p] = depth[fa] + 1;
23     father[p][0] = fa;
24     for(int i = 1; (1 << i) <= depth[p]; i++)
25         father[p][i] = father[father[p][i - 1]][i - 1];
26     for(int i = head[p]; i ; i = G[i].next)
27         if(G[i].v != fa)
28             dfs(G[i].v , p);
29 }
30 int lca(int u , int v)
31 {
32     if(depth[u] < depth[v])
33         swap(u , v);
34     while(depth[u] > depth[v])
35         u = father[u][lg[depth[u] - depth[v]] - 1];
36     if(u == v)
37         return u;
38     for(int i = lg[depth[u]] - 1; i >= 0; i--)
39         if(father[u][i] != father[v][i])
40             u = father[u][i] , v = father[v][i];
41     return father[u][0];    
42         
43 }
44 int main()
45 {
46     int u , v;
47     scanf("%d%d%d" , &n , &m , &s);
48     for(int i = 1; i < n; i++)
49     {
50         scanf("%d%d" , &u , &v);
51         add(u , v);
52         add(v , u);    
53     }
54     dfs(s , 0);
55     for(int i = 1; i <= n; i++)
56         lg[i] = lg[i - 1] + (1 << lg[i - 1] == i);
57     for(int i = 1; i <= m; i++)
58     {
59         scanf("%d%d", &u , &v);
60         printf("%d\n" , lca(u , v));    
61     }
62     return 0;
63 }

最近公共祖先

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!