洛谷-P3379 【模板】最近公共祖先(LCA)
作者:互联网
【模板】最近公共祖先(LCA)
倍增 lca 模板
真心觉得二进制太奇妙了
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
#define endl '\n'
const int maxn = 5e5 + 10;
vector<int>gra[maxn];
int fa[maxn][25], dep[maxn];
int n, m, s;
void dfs(int now, int pre, int cur)
{
if(dep[now]) return;
dep[now] = cur;
fa[now][0] = pre;
for(int i=0; i<gra[now].size(); i++)
{
int nex = gra[now][i];
if(nex == pre) continue;
dfs(nex, now, cur + 1);
}
}
void init_lca()
{
for(int i=1; i<=20; i++)
for(int j=1; j<=n; j++)
fa[j][i] = fa[fa[j][i-1]][i-1];
}
int lca(int a, int b)
{
if(dep[a] < dep[b]) swap(a, b);
int dif = dep[a] - dep[b];
for(int i=20; i>=0; i--)
{
if(dif >= (1 << i))
{
a = fa[a][i];
dif -= 1 << i;
}
}
if(a == b) return a;
for(int i=20; i>=0; i--)
{
if(fa[a][i] != fa[b][i])
{
a = fa[a][i];
b = fa[b][i];
}
}
return fa[a][0];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> s;
for(int i=1; i<n; i++)
{
int x, y;
cin >> x >> y;
gra[x].push_back(y);
gra[y].push_back(x);
}
dfs(s, s, 1);
init_lca();
while(m--)
{
int x, y;
cin >> x >> y;
cout << lca(x, y) << endl;
}
return 0;
}
标签:dep,now,洛谷,int,P3379,fa,maxn,LCA,include 来源: https://www.cnblogs.com/dgsvygd/p/16438180.html