LCA
LCA(Lowest Common Ancestors),即最近公共祖先,是指在有根树中,找出某两个结点u和v最近的公共祖先。
对于有根树T的两个结点u、v,最近公共祖先LCA(T,u,v)表示一个结点x,满足x是u、v的祖先且x的深度尽可能大。
另一种理解方式是把T理解为一个无向无环图,而LCA(T,u,v)即u到v的最短路上深度最小的点。
这里给出一个LCA的例子:
对于T=<V,E>
V={1,2,3,4,5}
E={(1,2),(1,3),(3,4),(3,5)}
则有:
LCA(T,5,2)=1
LCA(T,3,4)=3
LCA(T,4,5)=3
Tarjan
Tarjan算法是基于对图深度优先搜索的算法,每个强连通分量为搜索树中的一棵子树。搜索时,把当前搜索树中未处理的节点加入一个堆栈,回溯时可以判断栈顶到栈中的节点是否为一个强连通分量。
模板
题
POJ【1330】
传送门
CODE
#include <algorithm>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <list>
#include <map>
#include <iomanip>
#include <iostream>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
const int maxn = 1e4 + 7;
typedef long long ull;
inline int read() {
int s = 0, w = 1;
char ch = getchar();
while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
return s * w;
}
int T, n, t, a, b;
int in[maxn], fa[maxn], depth[maxn];
vector <int>m[maxn];
void dfs(int pre, int rt) {
depth[rt] = depth[pre] + 1;
fa[rt] = pre;
for (int i = 0; i < m[rt].size(); ++i) {
dfs(rt, m[rt][i]);
}
}
int lca(int a, int b) {
if (depth[a] > depth[b])
swap(a, b);
while (depth[b] > depth[a])
b=fa[b];
while (a!=b)
a=fa[a],b=fa[b];
return a;
}
int main() {
T = read();
while (T--) {
n = read();
for (int i = 1; i <= n; ++i) m[i].clear();
memset(in, 0, sizeof(in));
for (int i = 1; i < n; ++i) {
int x, y;
x = read(), y = read();
m[x].push_back(y);
++in[y];
}
depth[0] = -1;
int rt = 0;
for (int i = 1; i <= n && rt == 0; ++i) {
if (in[i] == 0)
rt = i;
}
dfs(0, rt);
a = read(), b = read();
printf("%d\n", lca(a, b));
}
return 0;
}