Splay板子求调,P3391【模板】文艺平衡树
  • 板块学术版
  • 楼主zhanglh
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/11/13 23:15
  • 上次更新2023/11/13 23:57:41
查看原帖
Splay板子求调,P3391【模板】文艺平衡树
726862
zhanglh楼主2023/11/13 23:15

Problem Link: P3391【模板】文艺平衡树

Splay板子,0pts,全TLE。感谢!

#include <iostream>
#include <cstdio>

using namespace std;

const int N = 100010;

int n, m;
int root, idx;
struct Node
{
    int son[2], father, v;
    int cnt, lazytag;
    
    void init(int _father, int _v)
    {
        cnt = 1;
        father = _father;
        v = _v;
    }
}tr[N];

void pushup(int x)
{
    tr[x].cnt = tr[tr[x].son[0]].cnt + tr[tr[x].son[1]].cnt + 1;
}

void pushdown(int x)
{
    if (tr[x].lazytag)
    {
        swap(tr[x].son[0], tr[x].son[1]);
        tr[tr[x].son[0]].lazytag ^= 1;
        tr[tr[x].son[1]].lazytag ^= 1;
        tr[x].lazytag = 0;
    }
}

void rotate(int x)
{
    int y = tr[x].father, z = tr[y].father;
    int k = tr[y].son[1] == x;
    tr[z].son[tr[z].son[1] == y] = x, tr[x].father = z;
    tr[y].son[k] = tr[x].son[k ^ 1], tr[tr[x].son[k ^ 1]].father = y;
    tr[x].son[k ^ 1] = y, tr[y].father = x;
    pushup(x), pushup(y);
}

void splay(int x, int k)
{
    while (tr[x].father != k)
    {
        int y = tr[x].father, z = tr[y].father;
        if (z != k)
        {
            if ((tr[y].son[1] == x) ^ (tr[z].son[1] == y)) rotate(x);
            else rotate(y);
        }
        rotate(x);
    }
    if (!k) root = x;
}

void insert(int v)
{
    int u = root, p = 0;
    while (u) p = u, u = tr[u].son[v > tr[u].v];
    u = ++ idx;
    if (p) tr[p].son[v > tr[p].v] = u;
    tr[u].init(p, v);
    splay(u, 0);
}

int get(int x)
{
    int u = root;
    while (true)
    {
        pushdown(u);
        if (tr[tr[u].son[0]].cnt >= x) u = tr[u].son[0];
        else if (tr[tr[u].son[0]].cnt + 1 == x) return u;
        else u = tr[u].son[1], x -= tr[tr[u].son[0]].cnt + 1;
    }
    return -1;
}

void output(int root)
{
    pushdown(root);
    if (tr[root].son[0]) output(tr[root].son[0]);
    if (tr[root].v >= 1 && tr[root].v <= n) printf("%d ", tr[root].v);
    if (tr[root].son[1]) output(tr[root].son[1]);
}

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 0; i <= n + 1; i ++ ) insert(i);
    
    while (m -- )
    {
        int l, r;
        scanf("%d%d", &l, &r);
        l = get(l), r = get(r + 2);
        splay(l, 0), splay(r, l);
        tr[tr[r].son[0]].lazytag ^= 1;
    }
    
    output(root);
    
    return 0;
}
2023/11/13 23:15
加载中...