Cod sursa(job #3321945)

Utilizator mihaigeorgescuGeorgescu Mihai mihaigeorgescu Data 11 noiembrie 2025 19:48:46
Problema Secv8 Scor 25
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.6 kb
#include <fstream>

using namespace std;
ifstream fcin("secv8.in");
ofstream fout("secv8.out");
int q,x,y;
char ch;
struct treap
{
    int x,p,ok,nr;
    treap *st, *dr;
    treap(int val) : x(val), p(rand()), ok(0), nr(1), st(nullptr), dr(nullptr) {};
};
treap* root=nullptr;
inline void push(treap* t)
{
    if(t && t->ok)
    {
        t->ok^=1;
        swap(t->st, t->dr);
        if(t->st) t->st->ok^=1;
        if(t->dr) t->dr->ok^=1;
    }
}
inline int cnt(treap* t)
{
    return (t ? t->nr : 0);
}
inline void update(treap* t)
{
    if(t) t->nr=1+cnt(t->st)+cnt(t->dr);
}
inline void split(treap* t, treap* &l, treap* &r, int poz, int add=0)
{
    push(t);
    if(!t) return void(l=r=nullptr);
    int cpoz=add+cnt(t->st);
    if(cpoz<poz) split(t->dr, t->dr, r, poz, cpoz+1), l=t;
    else split(t->st, l, t->st,poz, add), r=t;
    update(t);
}
inline void merge(treap* &t, treap* l, treap* r)
{
    push(l), push(r);
    if(!l || !r)
        return void(l ? t=l : t=r);
    if(l->p > r->p)
        merge(l->dr, l->dr, r), t=l;
    else
        merge(r->st, l, r->st), t=r;
    update(t);
}
inline void insert(treap* &nod, treap* t,  int poz)
{
    treap *t1, *t2;
    split(nod, t1, t2, poz);
    merge(nod,t1,t);
    merge(nod,nod,t2);
}
inline void erase(treap* &nod, int st, int dr)
{
    treap *t1, *t2, *t3;
    split(nod,t1,t2,st);
    split(t2,t2,t3,dr-st+1);
    merge(nod,t1,t3);
}
inline void reverse(treap* &nod, int st, int dr)
{
    treap *t1, *t2, *t3;
    split(nod,t1,t2,st);
    split(t2,t2,t3,dr-st+1);
    if(t2) t2->ok^=1;
    merge(nod, t1, t2);
    merge(nod, nod, t3);
}
inline int kth(treap* t, int poz, int add=0)
{
    if(!t) return -1;
    int cpoz=add+cnt(t->st)+1;
    if(poz==cpoz) return t->x;
    return (poz>cpoz ? kth(t->dr, poz, cpoz) : kth(t->st, poz, add));
}
inline void print(treap* t)
{
    if(t)
    {
        push(t);
        if(t->st) print(t->st);
        if(t) fout<<t->x<<" ";
        if(t->dr) print(t->dr);
    }
}
int main()
{
    fcin>>q>>x;
    while(q--)
    {
        fcin>>ch;
        if(ch=='I')
        {
            fcin>>x>>y;
            x--;
            insert(root, new treap(y), x);
        }
        if(ch=='A')
        {
            fcin>>x;
            fout<<kth(root, x)<<'\n';
        }
        if(ch=='R')
        {
            fcin>>x>>y;
            x--, y--;
            reverse(root,x,y);
        }
        if(ch=='D')
        {
            fcin>>x>>y;
            x--, y--;
            erase(root,x,y);
        }
    }
    print(root);
    return 0;
}