倍增 构造O(nlogn),在线(单次)查询O(logn)
tarjin 构造O(n) ,离线(全部)查询O(N+M)
根据题目 洛谷P3379【模板】最近公共祖先 的样例测试,tarjin和倍增不能通过占用的时间或空间评判高下,谁占优势应该跟数据的特征有关。
洛谷P3379【模板】最近公共祖先
倍增方法
构造fa数组的正确写法是这样的
for(int i=1; i<=20; i++){
fa[x][i] = fa[fa[x][i-1]][i-1];
}
然而第一遍错写成了这样
for(int i=1; i<=20; i++){
fa[x][i] = fa[father][i-1];
}
这显然是错误的,不是方法他的父亲的上2^i-1个节点,而是访问它的上2^i-1个节点的上2^i-1个节点
引以为戒
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <stack>
#include <string>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>
typedef long long int LL;
const int N = 5e5+5;
int fa[N][22],depth[N],head[N];
int n,m,s,u,v;
int idx;
struct Edge
{
int to,nxt;
}edg[N<<1];
void addEdge(int fr,int to)
{
edg[idx].to = to;
edg[idx].nxt = head[fr];
head[fr] = idx++;
}
void build(int x,int father)
{
fa[x][0] = father;
depth[x] = depth[father]+1;
for(int i=1; i<=20; i++){
fa[x][i] = fa[fa[x][i-1]][i-1];
}
for(int e=head[x]; e; e=edg[e].nxt){
int y = edg[e].to;
if(y!=father) build(y,x);
}
}
int lca(int x,int y)
{
if(depth[x] < depth[y]) std::swap(x,y);
for(int i=20; i>=0; i--){
if(fa[x][i]) if(depth[fa[x][i]]>=depth[y]){
x = fa[x][i];
if(depth[x] == depth[y]) break;
}
}
if(x == y) return x;
for(int i=20; i>=0; i--){
if(fa[x][i]) if(fa[x][i] != fa[y][i]){
x = fa[x][i];
y = fa[y][i];
}
}
return fa[y][0];
}
int main()
{
//freopen("D:\\EdgeDownloadPlace\\P3379_2.in","r",stdin);
idx = 2;
scanf("%d%d%d",&n,&m,&s);
for(int i=1; i<n; i++){
scanf("%d%d",&u,&v);
addEdge(u,v); addEdge(v,u);
}
build(s,0);
for(int i=0; i<m; i++){
scanf("%d%d",&u,&v);
printf("%d\n",lca(u,v));
}
return 0;
}
倍增方法可以提前算log优化
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <stack>
#include <string>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>
typedef long long int LL;
const int N = 5e5+5;
int fa[N][22],depth[N],head[N],old_brother[N];
int n,m,s,u,v;
int idx;
struct Edge
{
int to,nxt;
}edg[N<<1];
void addEdge(int fr,int to)
{
edg[idx].to = to;
edg[idx].nxt = head[fr];
head[fr] = idx++;
}
void build(int x,int father)
{
fa[x][0] = father;
depth[x] = depth