LCA
Asahina_Mafuyu · · 个人记录
倍增法
#include <bits/stdc++.h>
using namespace std;
int n, m, s, t;
int dep[500005], f[500005][25];
vector<int> v[500005];
void dfs(int cur, int fa)
{
dep[cur] = dep[fa] + 1;
f[cur][0] = fa;
for(int i = 0; i < v[cur].size(); i ++)
if(v[cur][i] != fa) dfs(v[cur][i], cur);
return ;
}
void lifting()
{
for(int i = 1; i <= t; i ++)
for(int j = 1; j <= n; j ++)//枚举节点
f[j][i] = f[f[j][i - 1]][i - 1];
return ;
}
int lca(int x, int y)//x更深
{
if(dep[x] < dep[y]) swap(x, y);
for(int i = t; i >= 0; i --)
if(dep[f[x][i]] >= dep[y]) x = f[x][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()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n >> m >> s;
t = (int)(log(n) / log(2)) + 1;//最大深度
for(int i = 1; i < n; i ++)
{
int x, y;
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
dfs(s, 0);
lifting();
for(int i = 1; i <= m; i ++)
{
int x, y;
cin >> x >> y;
cout << lca(x, y) << "\n";
}
return 0;
}
Tarjan
#include <bits/stdc++.h>
using namespace std;
int n, t, s;
int fa[500005];
int ans[500005];
bool vis[500005];
vector<int> v[500005];
struct node {
int to, q;
};
vector<node> q[500005];
int find(int x) {
return x == fa[x] ? fa[x] : fa[x] = find(fa[x]);
}
void dfs(int cur, int f) {
vis[cur] = true;
for(int i = 0; i < v[cur].size(); i ++)
if(v[cur][i] != f) {
dfs(v[cur][i], cur);
fa[v[cur][i]] = cur;
}
for(int i = 0; i < q[cur].size(); i ++) {
node x = q[cur][i];
if(vis[x.to]) ans[x.q] = find(x.to);
}
return ;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n >> t >> s;
for(int i = 1; i <= n; i ++) fa[i] = i;
for(int i = 1; i < n; i ++) {
int x, y;
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
for(int i = 1; i <= t; i ++) {
int x, y;
cin >> x >> y;
q[x].push_back({y, i});
q[y].push_back({x, i});
}
dfs(s, 0);
for(int i = 1; i <= t; i ++)
cout << ans[i] << "\n";
return 0;
}