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];
}

發佈了275 篇原創文章 · 獲贊 11 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章