0pts 求调

P3391 【模板】文艺平衡树

北射天狼 @ 2023-07-22 12:02:36

#include <bits/stdc++.h>
using namespace std;
inline int read(){
    int s = 0,f = 1;char c = getchar();
    while (!isdigit(c)){if (c == '-')f = -1;c = getchar();}
    while (isdigit(c)){s = (s << 3) + (s << 1) + (c ^ 48);c = getchar();}
    return s*f;
}
const int N = 1e5 + 5;
int n,m;
struct Splay{
    int root,idx;
    struct node{
        int s[2],val,p,tag,size;
    }tr[N<<1];
    void pushup(int x){
        tr[x].size = tr[tr[x].s[0]].size + tr[tr[x].s[1]].size + 1;
    }
    void pushdown(int x){
        if (tr[x].tag){
            tr[tr[x].s[0]].tag ^= 1;
            tr[tr[x].s[1]].tag ^= 1;
            swap(tr[x].s[0],tr[x].s[1]);
            tr[x].tag = 0;
        }
    }
    void rotate(int x){
        int y = tr[x].p,z = tr[y].p;
        pushdown(z);pushdown(y),pushdown(x);
        int k = (tr[y].s[1] == x);
        tr[y].s[k] = tr[x].s[k^1];
        tr[tr[x].s[k^1]].p = y;
        tr[x].s[k^1] = y;
        tr[y].p = x;
        tr[z].s[tr[z].s[1] == y] = x;
        tr[x].p = z;
        pushup(y);
        pushup(x);
    }
    void splay(int x,int k){
        while (tr[x].p != k){
            int y = tr[x].p,z = tr[y].p;
            if (z != k)
                (tr[z].s[0] == y) ^ (tr[y].s[1] == x) ? rotate(y) : rotate(x);
            rotate(x);
        }
        if (!k)
            root = x;
    }
    void insert(int v){
        int x = root,p = 0;
        while (tr[x].s[v > tr[x].val] && tr[x].val != v){
            p = x;
            x = tr[x].s[v > tr[x].val];
        }
        x = ++idx;
        tr[x].p = p;
        tr[p].s[v > tr[p].val] = x;
        tr[x].val = v;
        tr[x].tag = 0;
        tr[x].size = 1;
        splay(x,0);
    }
    int find(int val){
        int x = root;
        while (1){
            pushdown(x);
            if (val <= tr[tr[x].s[0]].size)
                x = tr[x].s[0];
            else {
                val -= tr[tr[x].s[0]].size+1;
                if (!val)
                    return x;
                x = tr[x].s[1];     
            }
        }
    }
    void reverse(int x,int y){
        x--,y++;
        int l = find(x),r = find(y);
        splay(l,0);
        splay(r,l);
        int node = tr[r].s[0];
        tr[node].tag ^= 1;
    }
    void query(int x){
        pushdown(x);
        if (tr[x].s[0])
            query(tr[x].s[0]);
        if (tr[x].val != -2e9 && tr[x].val != 2e9)
            printf("%d ",tr[x].val);
        if (tr[x].s[1])
            query(tr[x].s[1]);
    }
}splay;
int main()
{
    n = read(),m = read();
    splay.insert(-2e9),splay.insert(2e9);
    for (int i=1;i<=n;i++)
        splay.insert(i);
    for (int i=1,u,v;i<=n;i++)
    {
        u = read();v = read();
        splay.reverse(u+1,v+1);
    }
    splay.query(splay.root);
    return 0;
}

|