RMQ在线求LCA

#include<bits/stdc++.h>

using namespace std;

#define begin Begin
#define next Next
#define rank Rank

#define REP(i, a, b) for (int i = (a), _end_ = (b); i <= _end_; ++i)
#define ER(i, a) for (int i = begin[a]; i; i = next[i])
#define debug(...) fprintf(stderr, __VA_ARGS__)

template<typename T> inline bool chkmin(T &a, const T &b){ return a > b ? a = b, 1 : 0; }
template<typename T> inline bool chkmax(T &a, const T &b){ return a < b ? a = b, 1 : 0; }

template<class T> inline T read()
{
    T sum = 0, fg = 1, c = getchar();
    while (c < '0' || c > '9') { if (c == '-') fg = -1; c = getchar(); }
    while (c >= '0' && c <= '9') sum = sum * 10 + c - '0', c = getchar();
    return sum * fg;
}

typedef long long LL;

const int dmax = 300100, oo = 0x3f3f3f3f;

int N, M;

int begin[dmax], next[dmax], to[dmax], cnt = 0;

void add(const int &x, const int &y, const int &type = 1)
{
    to[++cnt] = y;
    next[cnt] = begin[x];
    begin[x] = cnt;
    if (type) add(y, x, 0);
}

int lg[dmax];

int rank[dmax], dis[dmax], cur = 0, Dis = 0;

int rmq[20][dmax];

void dfs(const int &x)
{
    rank[x] = ++cur, rmq[0][cur] = x;
    ER(i, x)
        if (!rank[to[i]])
        {
            dis[to[i]] = dis[x] + 1, dfs(to[i]);
            rmq[0][++cur] = x;
        }
}

inline int Min(const int &x, const int &y) { return dis[x] < dis[y] ? x : y; }

inline void log_init() { REP(i, 1, cur) { lg[i] = log(i) / log(2); debug("%d\n", lg[i]); } }

inline void rmq_init()
{
    int N = cur;
    REP(i, 1, lg[N])
        REP(j, 1, N - (1 << i) + 1)
            rmq[i][j] = Min(rmq[i - 1][j], rmq[i - 1][j + (1 << (i - 1))]);
}

inline int LCA(int x, int y)
{
    x = rank[x], y = rank[y];
    if (x > y) swap(x, y);
    int k = lg[y - x];
    return Min(rmq[k][x], rmq[k][x + (1 << k) + 1]);
}

inline void init() { dis[1] = 1, dfs(1), log_init(), rmq_init(); }

int main()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    N = read<int>(), M = read<int>();
    REP(i, 1, N - 1) add(read<int>(), read<int>());
    init();
    while (M--) printf("%d\n", LCA(read<int>(), read<int>()));
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值