首页 > 其他 > 详细

通用动态树(Link-Cut Tree)模板

时间:2019-02-24 11:03:48      阅读:221      评论:0      收藏:0      [点我收藏+]

一个没有维护任何东西的动态树模板

忘了怎么写可以直接来粘

int ch[300010][2], fa[300010], st[300010];
bool lazy[300010];

bool nroot(int x) { return ch[fa[x]][0] == x || ch[fa[x]][1] == x; }
void rev(int x) { swap(ch[x][0], ch[x][1]), lazy[x] ^= 1; }
void pushup(int x) { /*维护一个pre*/ }

void pushdown(int x)
{
    if (lazy[x])
    {
        if (ch[x][0]) rev(ch[x][0]);
        if (ch[x][1]) rev(ch[x][1]);
        lazy[x] = 0;
    }
}

void rotate(int x)
{
    int y = fa[x], z = fa[y], k = ch[y][1] == x, w = ch[x][k ^ 1];
    if (nroot(y)) { ch[z][ch[z][1] == y] = x; } ch[x][k ^ 1] = y, ch[y][k] = w;
    if (w) { fa[w] = y; } fa[y] = x; fa[x] = z; pushup(y), pushup(x);
}

void splay(int x)
{
    int y = x, top = 0;
    st[++top] = y;
    while (nroot(y)) st[++top] = y = fa[y];
    while (top > 0) pushdown(st[top--]);
    while (nroot(x))
    {
        int y = fa[x], z = fa[y];
        if (nroot(y)) rotate((ch[y][1] == x) ^ (ch[z][1] == y) ? x : y);
        rotate(x);
    }
    pushup(x);
}

void access(int x)
{
    for (int y = 0; x > 0; x = fa[y = x])
        splay(x), ch[x][1] = y, pushup(x);
}

void makert(int x)
{
    access(x), splay(x), rev(x);
}

int findrt(int x)
{
    access(x), splay(x);
    while (ch[x][0]) pushdown(x), x = ch[x][0];
    return x;
}

void link(int x, int y)
{
    makert(x);
    if (findrt(y) != x) fa[x] = y;
}

void cut(int x, int y)
{
    makert(x);
    if (findrt(y) == x && fa[x] == y && ch[x][1] == 0)
        ch[y][0] = fa[x] = 0, pushup(y);
}

通用动态树(Link-Cut Tree)模板

原文:https://www.cnblogs.com/oier/p/10425484.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!