题意
给出一棵节点数为NNN的树,有MMM次询问,每次询问两个节点的最近公共祖先。
思路
树上倍增。
代码
#include<queue>
#include<cmath>
#include<cstdio>
using namespace std;
struct node{
int to, next;
}e[1000001];
int N, M, S, tot, t;
int d[500001], head[500001], f[500001][20];
void bfs(int S)
{
int x, y;
queue<int> q;
d[S] = 1;
q.push(S);
while (q.size())
{
x = q.front();
q.pop();
for (int i = head[x]; i; i = e[i].next)
{
y = e[i].to;
if (d[y]) continue;
d[y] = d[x] + 1;
f[y][0] = x;
for (int j = 1; j <= t; j++) f[y][j] = f[f[y][j - 1]][j - 1];
q.push(y);
}
}
}
int LCA(int x,int y)
{
if (d[x] > d[y]) swap(x, y);
for (int i = t; i >= 0; i--) if (d[f[y][i]] >= d[x]) y = f[y][i];
if (x == y) return x;
for (int i = t; i >= 0; i--)
if (f[x][i] != f[y][i])
{
x = f[x][i];
y = f[y][i];
}
return f[x][0];
}
int main()
{
scanf("%d %d %d", &N, &M, &S);
int x, y;
t = log(N) / log(2);
for (int i = 1; i < N; i++)
{
scanf("%d %d", &x, &y);
e[++tot] = (node){y, head[x]};
head[x] = tot;
e[++tot] = (node){x, head[y]};
head[y] = tot;
}
bfs(S);
while (M--)
{
scanf("%d %d", &x, &y);
printf("%d\n", LCA(x, y));
}
}