给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先。
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<math.h>
#include<set>
using namespace std;
inline int read()//快读
{
char c = getchar(); int x = 0, f = 1;
while (c<'0' || c>'9') { if (c == '-')f = -1; c = getchar(); }
while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
return x * f;
}
int n, tot = 0;
struct z {
int t, nex;
}e[1000010];
int dep[500001];
int f[500001][22];
int lg[500001];
int head[500010];
void add(int x, int y) {
e[++tot].t = y;
e[tot].nex = head[x];
head[x] = tot;
}
void dfs(int x, int fat)
{
dep[x] = dep[fat] + 1;
f[x][0] = fat;
for (int i = 1; (1 << i) <= dep[x]; i++)
{
f[x][i] = f[f[x][i - 1]][i - 1];//2^i=2^(i-1)+2^(i-1)
}
for (int i = head[x]; i; i = e[i].nex)
if (e[i].t != fat) dfs(e[i].t, x);
}
int lca(int x, int y)
{
if (dep[x] < dep[y])
{
swap(x, y);
}
while (dep[x] != dep[y])
{
x = f[x][lg[dep[x] - dep[y]] - 1];
}
if (x == y)
{
return x;
}
for (int i = lg[dep[x]]; i >= 0; i--)
{
if (f[x][i] != f[y][i])
{
x = f[x][i];
y = f[y][i];
}
}
return f[x][0];
}
int main()
{
int m, s, a, b, x, y;
n = read(), m = read(), s = read();
for (int i = 1; i < n; i++)
{
a = read(), b = read();
add(a, b);
add(b, a);
}
for (int i = 1; i <= n; i++)
{
lg[i] = lg[i - 1];
if (i == (1 << lg[i - 1])) lg[i]++;//lg为log(i)+1
}
dfs(s, 0);
for (int i = 1; i <= m; i++) {
x = read(), y = read();
printf("%d\n", lca(x, y));
}
return 0;
}
样例输入
5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5
样例输出
4 4 1 4 4