核心:
pre[i][j] 为节点 i 向上2的j次方处的祖先。
pre[i][j] = pre[pre[i][j-1]][j-1]
#include <bits\stdc++.h>
const int maxn = 10000 + 10;
using namespace std;
int pre[maxn][50], n, root, dis[maxn], dep[maxn];
vector<int> v[maxn];
void dfs(int p) {
vector<int>::iterator it;
for(it = v[p].begin(); it != v[p].end(); it++) {
int s = *it;
dep[s] = dep[p] + 1;
dis[s] = dis[p] + 1;
dfs(s);
}
}
void init() {
for(int j = 1; (1 << j) <= n; j++)
for(int i = 1; i <= n; i++) pre[i][j] = pre[pre[i][j-1]][j-1];
}
void add(int a, int b) {
v[a].push_back(b);
pre[b][0] = a;
}
int lca(int a, int b) {
if(dep[a] > dep[b]) swap(a, b);
int m = dep[b] - dep[a];
for(int i = 0; (1 << i) <= m; i++) {
if(m & (1 << i)) b = pre[b][i];
}
if(a != b) {
for(int i = (int)log2(n); i >= 0; i--) {
if(pre[a][i] != pre[b][i]) {
a = pre[a][i];
b = pre[b][i];
}
}
a = pre[a][0];
}
return a;
}
int main() {
cin >> n >> root;
for(int i = 1; i < n; i++) {
int a, b;
cin >> a >> b;
add(a, b);
}
init();
dfs(root);
cout << "LCA is located on node : " << lca(16, 9) << endl;
system("pause");
return 0;
}