传送门
核心函数
int lca(int u, int v)
{
while (top[u] != top[v])
{
if (dep[top[u]] < dep[top[v]])
swap(u, v);
u = fa[top[u]];
}
if (dep[u] < dep[v])
return u;
else
return v;
}
代码
#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
#define fir(i, a, b) for (int i = (a); i <= (b); i++)
#define rif(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
#define init_h memset(h, -1, sizeof h), idx = 0;
#define lowbit(x) x &(-x)
const int N = 5e5 + 10;
int n, m, root;
int h[N], e[N << 1], ne[N << 1], idx;
int top[N], fa[N], sz[N], son[N], dep[N];
void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
void dfs1(int u, int father, int depth)
{
dep[u] = depth, fa[u] = father, sz[u] = 1;
for (int i = h[u]; ~i; i = ne[i])
{
int t = e[i];
if (t == father)
continue;
dfs1(t, u, depth + 1);
sz[u] += sz[t];
if (son[u] == 0 || sz[son[u]] < sz[t])
{
son[u] = t;
}
}
}
void dfs2(int u, int v)
{
top[u] = v;
if (son[u] == 0)
return;
dfs2(son[u], v);
for (int i = h[u]; ~i; i = ne[i])
{
int t = e[i];
if(t==fa[u]||t==son[u]) continue;
dfs2(t,t);
}
}
int lca(int u, int v)
{
while (top[u] != top[v])
{
if (dep[top[u]] < dep[top[v]])
swap(u, v);
u = fa[top[u]];
}
if (dep[u] < dep[v])
return u;
else
return v;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int StartTime = clock();
#endif
scanf("%d%d%d", &n, &m, &root);
init_h;
fir(i, 1, n - 1)
{
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
add(b, a);
}
dfs1(root, -1, 1);
dfs2(root,root);
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",lca(a,b));
}
#ifndef ONLINE_JUDGE
printf("Run_Time = %d ms\n", clock() - StartTime);
#endif
return 0;
}