LCA
倍增
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 4e4 + 10, M = 18;
int n, m;
int fa[N][M], depth[N];
vector<int> G[N];
queue<int> q;
void add(int a, int b)
{
G[a].push_back(b);
}
void bfs(int root)
{
q.push(root);
memset(depth, 0x3f, sizeof depth);
depth[0] = 0;
depth[root] = 1;
while(!q.empty())
{
int t = q.front();
q.pop();
for (auto to : G[t])
{
if (depth[to] != depth[t] - 1)
{
depth[to] = depth[t] + 1;
fa[to][0] = t;
q.push(to);
for (int k = 1; k < M; k++)
fa[to][k] = fa[fa[to][k-1]][k-1];
}
}
}
}
int lca(int a, int b)
{
if (depth[a] < depth[b])
swap(a, b);
for (int k = M-1; k >= 0; k--)
if (depth[fa[a][k]] >= depth[b])
a = fa[a][k];
if (a == b)
return a;
for (int k = M-1; k >= 0; k--)
if (fa[a][k] != fa[b][k])
{
a = fa[a][k];
b = fa[b][k];
}
return fa[a][0];
}