LCA

1.倍增法求LCA

struct edge
{
    int to;
    int next;
};
int tot,head[maxn];
edge e[maxn<<1];
void init()
{
    tot=0;
    memset(head,-1,sizeof(head));
}
void addedge(int u,int v)
{
    e[tot].to=v;
    e[tot].next=head[u];
    head[u]=tot;
    tot++;
}


struct LCA
{
    int dep[maxn];
    int fa[maxn][25];
    void initlca(int u,int f)
    {
        dep[u]=dep[f]+1;
        for(int i=1;i<=20;i++)fa[u][i]=fa[fa[u][i-1]][i-1];
        for(int i=head[u];i!=-1;i=e[i].next)
        {
            int to=e[i].to;
            if(to==f)continue;
            fa[to][0]=u;
            getlca(to,u);
        }
    }
    int lca(int x,int y)
    {
        if(dep[x]<dep[y])swap(x, y);
        for(int i=20;i>=0;i--)if(dep[fa[x][i]]>=dep[y])x=fa[x][i];
        if(x==y)return x;
        for(int i=20;i>=0;i--)if(fa[x][i]!=fa[y][i])x=fa[x][i],y=fa[y][i];
        return fa[x][0];
    }
}lca;

 

应用

1.求树链边上一个值。

Gym - 101889I  询问q次,每次询问带有特定边的MST是多少。

该题容易想到,先求出不带特定边的MST值v,每次询问加入特定边(u,v),如果边在MST边上输出v,如果不在MST上,则去掉(u->lca->v)上 的最大值。

对于树链上的操作,将其lca点找出后,很容易变成线性结构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值