Skip to content

Commit bc07e9b

Browse files
authored
利用Tarjan算法求最小公共祖先(LCA)
1 parent 4979af8 commit bc07e9b

File tree

1 file changed

+147
-0
lines changed

1 file changed

+147
-0
lines changed

Least-Common-Ancestor(Tarjan).cpp

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
#include <cstdio>
2+
3+
#define MAX_VERTEX_COUNT 100000
4+
#define MAX_EDGE_COUNT 100000
5+
6+
using namespace std;
7+
8+
struct vertex
9+
{
10+
int first_edge;
11+
bool finish;
12+
}V[MAX_VERTEX_COUNT];
13+
14+
struct edge
15+
{
16+
int endp, next;
17+
}E[MAX_EDGE_COUNT];
18+
19+
int ec = 1;
20+
21+
struct qvertex
22+
{
23+
int first_edge;
24+
}QV[MAX_VERTEX_COUNT];
25+
26+
struct qedge
27+
{
28+
int endp, next, ans;
29+
}QE[MAX_EDGE_COUNT];
30+
31+
int qec = 1;
32+
33+
int fa[MAX_VERTEX_COUNT], size[MAX_VERTEX_COUNT], ancestor[MAX_VERTEX_COUNT];
34+
35+
void add_edge(int u, int v)
36+
{
37+
E[ec].next = V[u].first_edge;
38+
V[u].first_edge = ec;
39+
E[ec].endp = v;
40+
ec++;
41+
}
42+
43+
void add_qedge(int u, int v)
44+
{
45+
QE[qec].next = QV[u].first_edge;
46+
QV[u].first_edge = qec;
47+
QE[qec].endp = v;
48+
qec++;
49+
}
50+
51+
void initial_set(int c)
52+
{
53+
for (int i = 1; i <= c; i++)
54+
{
55+
fa[i] = i;
56+
size[i] = 1;
57+
}
58+
}
59+
60+
int get_root(int x)
61+
{
62+
if (fa[x] == x)
63+
{
64+
return x;
65+
}
66+
return (fa[x] = get_root(fa[x]));
67+
}
68+
69+
void merge(int x, int y)
70+
{
71+
int rtx = get_root(x), rty = get_root(y);
72+
if (size[rtx] < size[rty])
73+
{
74+
fa[rtx] = rty;
75+
size[rty] += size[rtx];
76+
}
77+
else
78+
{
79+
fa[rty] = rtx;
80+
size[rtx] += size[rty];
81+
}
82+
}
83+
84+
void DFS(int u, int prev)
85+
{
86+
fa[u] = u;
87+
size[u] = 1;
88+
ancestor[get_root(u)] = u;
89+
90+
for (int cur = V[u].first_edge; cur != 0; cur = E[cur].next)
91+
{
92+
if (E[cur].endp != prev)
93+
{
94+
DFS(E[cur].endp, u);
95+
merge(u, E[cur].endp);
96+
ancestor[get_root(u)] = u;
97+
}
98+
}
99+
V[u].finish = true;
100+
101+
for (int cur = QV[u].first_edge; cur != 0; cur = QE[cur].next)
102+
{
103+
if (V[QE[cur].endp].finish == true)
104+
{
105+
QE[cur].ans = ancestor[get_root(QE[cur].endp)];
106+
}
107+
}
108+
}
109+
110+
int main()
111+
{
112+
int ivc, iqc;
113+
scanf("%d%d", &ivc, &iqc);
114+
115+
for (int i = 1; i < ivc; i++)
116+
{
117+
int u, v;
118+
scanf("%d%d", &u, &v);
119+
add_edge(u, v);
120+
add_edge(v, u);
121+
}
122+
123+
for (int i = 0; i < iqc; i++)
124+
{
125+
int u, v;
126+
scanf("%d%d", &u, &v);
127+
add_qedge(u, v);
128+
add_qedge(v, u);
129+
}
130+
131+
initial_set(ivc);
132+
133+
DFS(1, 0);
134+
135+
for (int i = 1; i <= ivc; i++)
136+
{
137+
for (int cur = QV[i].first_edge; cur != 0; cur = QE[cur].next)
138+
{
139+
if (QE[cur].ans != 0)
140+
{
141+
printf("The LCA of %d and %d is %d.\n", i, QE[cur].endp, QE[cur].ans);
142+
}
143+
}
144+
}
145+
146+
return 0;
147+
}

0 commit comments

Comments
 (0)