L i n k Link Link
l u o g u P 3379 luogu\ P3379 luogu P3379
D e s c r i p t i o n Description Description
S a m p l e Sample Sample I n p u t Input Input
5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5
S a m p l e Sample Sample O u t p u t Output Output
4
4
1
4
4
H i n t Hint Hint
T r a i n Train Train o f of of T h o u g h t Thought Thought
倍增求LCA
C o d e Code Code
#include<iostream>
#include<cstdio>
using namespace std;
int t, m, s, n;
int h[500005], deg[500005];
int l[500005], fa[500005][21];
struct node
{
int to, next;
}w[1000005];
void add(int x, int y)
{w[++t] = (node){y, h[x]}; h[x] = t;}
void dfs(int now, int fath)
{
fa[now][0] = fath; deg[now] = deg[fath] + 1;
for (int i = 1; i <= l[deg[now]]; ++i)
fa[now][i] = fa[fa[now][i - 1]][i - 1];//2^i = 2 * 2 ^ (i - 1)
for (int i = h[now]; i; i = w[i].next)
if (w[i].to != fath) dfs(w[i].to, now);
}
int LCA(int x, int y)
{
if (deg[x] < deg[y]) swap(x, y);
while (deg[x] > deg[y])
x = fa[x][l[deg[x] - deg[y]] - 1];//降到同一深度
if (x == y) return x;
for (int i = l[deg[x]] - 1; i >= 0; --i)
if (fa[x][i] != fa[y][i]) {
x = fa[x][i];
y = fa[y][i];
}
return fa[x][0];
}
int main()
{
int x, y;
scanf("%d%d%d", &n, &m, &s);
for (int i = 1; i < n; ++i)
{
scanf("%d%d", &x, &y);
add(x, y); add(y, x);
}
for (int i = 1; i <= n; ++i)
l[i] = l[i - 1] + (1 << l[i - 1] == i);//求log
dfs(s, 0);
for (int i = 1; i <= m; ++i)
{
int x, y; scanf("%d%d", &x, &y);
printf("%d\n", LCA(x, y));
}
}