LCA o(nlogn)

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <set>
#include <stack>
#include <algorithm>
#define LL long long 
using namespace std;
int read()
{
    int x = 0, f = 1; char ch = getchar();
    while(ch < '0' || ch > '9'){if(ch == '-') f *= -1; ch = getchar();}
    while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0'; ch = getchar();}
    return x * f;
}
const int MAXN = 100000 + 10;
const int INF = 0x3f3f3f3f;
int n, m, u, v, w, dfs_clock, tot, head[MAXN];
int dep[MAXN], id[MAXN], pos[MAXN], bin[30],fa[MAXN][30];
long long dis[MAXN];
struct Edge{int to, next,w;}edge[MAXN<<1];
void init(){tot = 0; memset(head, -1, sizeof(head));}
void addedge(int u, int v, int w)
{
    edge[tot].to = v; edge[tot].next = head[u]; edge[tot].w = w;head[u] = tot++;
    edge[tot].to = u; edge[tot].next = head[v]; edge[tot].w = w;head[v] = tot++;
}
void dfs(int x)
{
    id[x] = ++dfs_clock; pos[dfs_clock] = x;
    for(int i=1;bin[i] <= dep[x];i++)
        fa[x][i] = fa[fa[x][i-1]][i-1];
    for(int i=head[x];i!=-1;i=edge[i].next) if(edge[i].to != fa[x][0])
    {
        dep[edge[i].to] = dep[x] + 1;
        dis[edge[i].to] = dis[x] + edge[i].w;
        fa[edge[i].to][0] = x;
        dfs(edge[i].to);
    }
}
int lca(int x, int y)
{
    if(dep[x] > dep[y]) swap(x, y);
    int t = dep[y] - dep[x];
    for(int i=0;bin[i] <= t; i++) if(bin[i] & t) y = fa[y][i];
    for(int i=16;i>=0;i--) if(fa[x][i] != fa[y][i])
        x = fa[x][i], y = fa[y][i];
    return x == y ? x : fa[x][0];
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值