最近公共祖先 (LCA)

倍增法求LCA

洛谷P3379【模板】最近公共祖先(LCA)

时间复杂度预处理$O(n)$,询问$O(logn)$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// luogu-judger-enable-o2
#include<iostream>
#include<cstdio>
#include<cstring>

const int inf=0x7fffffff;
const int maxlog=25;

class LCA
{
private:
int n;
typedef struct EdgeNode
{
int to;
EdgeNode *next;
EdgeNode(int to,EdgeNode *nxt):to(to)
{
next=nxt;
}
~EdgeNode()
{
if(next!=NULL)
delete next;
}
}*Edge;

Edge *head;

void add(int u,int v)
{
head[u]=new EdgeNode(v,head[u]);
head[v]=new EdgeNode(u,head[v]);
}

int **father,*depth;

void dfs(int pos,int dad)
{
depth[pos]=depth[dad]+1;
father[pos][0]=dad;
for(int i=1;i<maxlog;i++)
father[pos][i]=father[father[pos][i-1]][i-1];
for(Edge node=head[pos];node;node=node->next)
if(node->to!=dad)
dfs(node->to,pos);
}

public:
LCA(int n):n(n)
{
head=new Edge[n+10];
memset(head,0,(n+10)*sizeof(Edge));
father=new int*[n+10];
for(int i=0;i<n+10;i++)
father[i]=new int[maxlog];
depth=new int[n+10];
memset(depth,0,(n+10)*sizeof(int));
}

~LCA()
{
delete [] head;
for(int i=0;i<n+10;i++)
delete [] father[i];
delete [] father;
delete [] depth;
}

void input_edge()
{
for(int i=1;i<n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v);
}
}

void Solve(int root)
{
dfs(root,0);
}

int get_LCA(int x,int y)
{
if(depth[x]<depth[y])
std::swap(x,y);
for(int i=maxlog-1;i>=0;i--)
if(depth[father[x][i]]>=depth[y])
x=father[x][i];
if(x==y)
return x;
for(int i=maxlog-1;i>=0;i--)
if(father[x][i]!=father[y][i])
x=father[x][i],y=father[y][i];
return father[x][0];
}

};

int main()
{
int n,s,T;
scanf("%d%d%d",&n,&T,&s);
LCA *Lca=new LCA(n);
Lca->input_edge();
Lca->Solve(s);
while(T--)
{
int x,y;
scanf("%d%d",&x,&y);
printf("%d\n",Lca->get_LCA(x,y));
}
delete Lca;
return 0;
}