【LCA练习 倍增 tarjin】 洛谷P3379【模板】最近公共祖先 P1967货车运输

本文讨论了洛谷P3379问题中最近公共祖先(LCA)的两种解法——倍增法和Tarjan算法。倍增法构造时间为O(nlogn),单次查询O(logn),而Tarjan法构造时间为O(n),但仅适用于离线查询,全部查询时间O(N+M)。文中指出,两种方法的优劣取决于具体数据特征,并提供了错误示例和优化建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

倍增 构造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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值