最近公共祖先(LCT)

來一發\(LCT\)\(LCA\)

\(LCT\)在時間上不佔據優點,碼量彷佛還比樹剖,倍增,\(Tarjan\)一點c++

可是倒是一道\(LCT\)的練手題spa

對於每個詢問,咱們只須要把其中一個點(咱們設爲a)先\(access\),這樣a到根節點的路徑就都在一棵\(Splay\)裏面了code

並且不難發現,有一個很妙的性質:若是兩個點不在一條路徑上(即\(lca!=a||lca!=b\))那麼b點\(access\)之後,b第一次到a到\(root\)\(Splay\)的上的點即爲\(LCA\)blog

而後咱們考慮在將另外一個點(咱們設爲b)與根的路徑打通,咱們仍是同樣一直\(Splay\),對於最後一棵\(Splay\)pdo

\(LCA\)即爲b第一次到a和rt的那一棵\(Splay\)的位置get

那麼a,b原本在一個\(Splay\)上呢?it

其實也是同樣的,咱們在分類討論class

1)若\(dep[a]>dep[b]\)那麼顯然不影響答案,答案就是b點im

2)若\(dep[a]<dep[b]\)那麼咱們在\(access(a)\)時候,a,b就已經不在一顆\(Splay\)裏了,因此也不影響答案top

代碼以下:

#include<bits/stdc++.h>
using namespace std;
#define il inline
#define re register
il int read()
{
    re int x = 0, f = 1; re char c = getchar();
    while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar();
    return x * f;
}
#define get_fa(x) (ch[1][fa[x]] == x)
#define isroot(x) (ch[1][fa[x]] == x || ch[0][fa[x]] == x)
#define updown(x) swap(ch[1][x], ch[0][x]), tag[x] ^= 1
#define rep(i, s, t) for(re int i = s; i <= t; ++ i)
#define maxn 500005
int n, m, s, ch[2][maxn], fa[maxn], st[maxn], top, tag[maxn];
il void pushdown(int x)
{
    if(tag[x])
    {
        if(ch[0][x]) updown(ch[0][x]);
        if(ch[1][x]) updown(ch[1][x]);
        tag[x] = 0;
    }
}
il void rotate(int x)
{
    int y = fa[x], z = fa[y], w = get_fa(x), k = get_fa(y);
    if(isroot(y)) ch[k][z] = x;
    if(ch[w ^ 1][x]) fa[ch[w ^ 1][x]] = y;
    fa[x] = z, fa[y] = x;
    ch[w][y] = ch[w ^ 1][x], ch[w ^ 1][x] = y;
}
il void Splay(int x)
{
    int y = x;
    st[++ top] = x;
    while(isroot(y)) st[++ top] = y = fa[y];
    while(top) pushdown(st[top --]);
    while(isroot(x))
    {
        int y = fa[x];
        if(isroot(y)) rotate(get_fa(x) == get_fa(y) ? y : x);
        rotate(x);
    }
}
il void access(int x)
{
    for(re int y = 0; x; x = fa[y = x]) Splay(x), ch[1][x] = y;
}
il void makeroot(int x) {access(x), Splay(x), updown(x);}
il void link(int a, int b) {makeroot(a), fa[a] = b;}
il int query(int a, int b)
{
    access(a);
    int ans = 0;
    for(; b; b = fa[ans = b]) Splay(b), ch[1][b] = ans;
    return ans;
}
int main()
{
    n = read(), m = read(), s = read();
    rep(i, 1, n - 1){int u = read(), v = read(); link(u, v);}
    makeroot(s);
    while(m --)
    {
        int a = read(), b = read();
        printf("%d\n", query(a, b));
    } 
    return 0;
}
相關文章
相關標籤/搜索