倍增算法
预处理 O(nlogn)
单次询问 O(logn)
void dfs(int u, int fa)
{
for (int i = hd[u]; i; i = g[i].nxt)
{
int v = g[i].to;
if (v == fa)
continue;
d[v] = d[u] + 1;
anc[v][0] = u;
dfs(v, u);
}
return;
}
void init()
{
for (int j = 1; j <= 18; j++)
for (int i = 1; i <= n; i++)
anc[i][j] = anc[anc[i][j - 1]][j - 1];
}
int LCA(int u, int v)
{
if (d[u] < d[v])
swap(u, v);
for (int i = 18; i >= 0; i--)
if (d[anc[u][i]] >= d[v])
u = anc[u][i];
if (u == v)
return u;
for (int i = 18; i >= 0; i--)
if (anc[u][i] != anc[v][i])
u = anc[u][i], v = anc[v][i];
return anc[u][0];
}
Tarjan算法(离线)
时间复杂度 O(n + m)
inline int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
void dfs(int u)
{
fa[u] = u;
vis[u] = 1;
for (int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
if (vis[v])
continue;
dfs(v);
fa[v] = u;
}
for (int i = 0; i < Q[u].size(); i++)
{
int v = Q[u][i].first;
if (!vis[v])
continue;
ans[Q[u][i].second] = find(v);
}
}
标签:return,anc,int,vis,dfs,fa,LCA From: https://www.cnblogs.com/xqk0225/p/16823298.html