\(\color{purple}{1.暴力}\)
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 10;
vector <int> vec[maxn];
int f[maxn];
int dep[maxn];
void dfs(int now, int fa);
int gt(int a, int b);
int main()
{
int n, m, s;
cin >> n >> m >> s;
for (int i = 1; i < n; ++i)
{
int x, y;
cin >> x >> y;
vec[x].push_back(y);
vec[y].push_back(x);
}
dfs(s, 0);
for (int i = 1; i <= m; ++i)
{
int x, y;
cin >> x >> y;
cout << gt(x, y) << '\n';
}
return 0;
}
void dfs(int now, int fa)
{
dep[now] = dep[fa] + 1;
f[now] = fa;
for (auto i : vec[now])
{
if (i != fa)
dfs(i, now);
}
}
int gt(int a, int b)
{
if (a == b)
{
return a;
}
if (dep[a] > dep[b])
{
swap(a, b);
}
while (dep[a] != dep[b])
{
b = f[b];
}
if (a == b)
return a;
while (f[a] != f[b])
{
a = f[a];
b = f[b];
}
return f[a];
}
\(\color{purple}{2.倍增}\)
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 10;
vector<int> vec[maxn];
int f[maxn][25];
int dep[maxn];
void dfs(int now, int fa);
int gt(int a, int b);
int main()
{
int n, m, s;
cin >> n >> m >> s;
for (int i = 1; i < n; ++i)
{
int x, y;
cin >> x >> y;
vec[x].push_back(y);
vec[y].push_back(x);
}
dfs(s, 0);
for (int i = 1; i <= m; ++i)
{
int x, y;
cin >> x >> y;
cout << gt(x, y) << '\n';
}
return 0;
}
void dfs(int now, int fa)
{
dep[now] = dep[fa] + 1;
f[now][0] = fa;
for (int i = 1; i <= 20; ++i)
{
f[now][i] = f[f[now][i - 1]][i - 1];
}
for (auto i : vec[now])
{
if (i != fa)
dfs(i, now);
}
}
int gt(int x, int y)
{
if (dep[x] < dep[y])
swap(x, y);
for (int i = 20; i >= 0; --i)
{
if (dep[f[x][i]] >= dep[y])
x = f[x][i];
if (x == y)
return x;
}
for (int i = 20; i >= 0; --i)
{
if (f[x][i] != f[y][i])
{
x = f[x][i];
y = f[y][i];
}
}
return f[x][0];
}
标签:int,back,dfs,dep,maxn,vec,LCA
From: https://www.cnblogs.com/xu-jh2024/p/18455304