Cod sursa(job #1783491)

Utilizator touristGennady Korotkevich tourist Data 19 octombrie 2016 00:54:44
Problema Secv8 Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.75 kb
#include <bits/stdc++.h>
#define MOD 1000000007

using namespace std;
ofstream fout("secv8.out");

struct T
{
    T *L,*R;
    int cnt,val,rev,pr;
    T(int x)
    {
        cnt=1;
        val=x;
        L=R=0;
        rev=0;
        pr = rand()%MOD;
    }
} *rad = 0;

inline int Cnt(T* nod)
{
    if(!nod) return 0;
    return nod->cnt;
}

inline void Propag(T *nod)
{
    if(!nod) return;
    if(!nod->rev) return;
    if(nod->L) nod->L->rev^=1;
    if(nod->R) nod->R->rev^=1;
    swap(nod->L,nod->R);
    nod->rev=0;
}

inline void Upd(T* nod)
{
    if(!nod) return;
    nod->cnt = 1 + Cnt(nod->L) + Cnt(nod->R);
}

T* Merge(T* L, T* R)
{
    Propag(L); Propag(R);
    if(!L) return R;
    if(!R) return L;
    if(L->pr > R->pr)
    {
        L->R = Merge(L->R,R);
        Upd(L);
        return L;
    }
    R->L = Merge(L,R->L);
    Upd(R);
    return R;
}

inline T* Find(T* nod, int poz)
{
    Propag(nod);
    if(Cnt(nod->L)+1==poz) return nod;
    if(Cnt(nod->L)+1<poz) return Find(nod->R,poz-Cnt(nod->L)-1);
    return Find(nod->L,poz);
}

pair <T*,T*> Split(T* nod, int k)
{
    Propag(nod);
    if(!nod) return make_pair((T*) 0 ,(T*) 0);
    if(Cnt(nod->L) + 1 > k)
    {
        pair <T*,T*> spl = Split(nod->L,k);
        nod->L = spl.second;
        Upd(nod);
        return make_pair(spl.first,nod);
    }

    pair <T*,T*> spl = Split(nod->R,k-Cnt(nod->L)-1);
    nod->R = spl.first;
    Upd(nod);
    return make_pair(nod,spl.second);
}

void Go(T* nod)
{
    Propag(nod);
    if(nod->L) Go(nod->L);
    if(nod) fout<<nod->val<<" ";
    if(nod->R) Go(nod->R);
}

int main()
{
    int n,x,y;
    char tip;
    ifstream cin("secv8.in");
    srand(time(0));
    cin>>n>>x;
    while(n--)
    {
        cin>>tip>>x;
        if(tip=='I')
        {
            cin>>y;
            pair <T*,T*> spl = Split(rad,x-1);
            T *nod = new T(y);
            rad=Merge(Merge(spl.first,nod),spl.second);
        }
        if(tip=='A')
        {
            pair <T*,T*> spl = Split(rad,x-1);
            pair <T*,T*> spl1 = Split(spl.second,1);
            fout<<spl1.first->val<<"\n";
            rad = Merge(Merge(spl.first,spl1.first),spl1.second);
        }
        if(tip=='D')
        {
            cin>>y;
            pair <T*,T*> spl = Split(rad,x-1);
            pair <T*,T*> spl1 = Split(spl.second,y-x+1);
            rad = Merge(spl.first,spl1.second);
        }
        if(tip=='R')
        {
            cin>>y;
            pair <T*,T*> spl = Split(rad,x-1);
            pair <T*,T*> spl1 = Split(spl.second,y-x+1);
            spl1.first->rev^=1;
            rad = Merge(Merge(spl.first,spl1.first),spl1.second);
        }
    }
    Go(rad);
    return 0;
}