Cod sursa(job #444595)

Utilizator DraStiKDragos Oprica DraStiK Data 20 aprilie 2010 22:04:47
Problema Nums Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.37 kb
#include <algorithm>
#include <fstream>
#include <string>
using namespace std;

#define INF 0x3f3f3f3f

ifstream fin ("nums.in");
ofstream fout ("nums.out");

struct node
{;
    string str;
    int key,priority;
    node *left,*right;
} *rad,*nil;
int n;

void init ()
{
    nil=new node;

    nil->str="";
    nil->key=0;
    nil->priority=-INF;
    nil->left=nil->right=0;
    rad=nil;
}

int cmp (string a,string b)
{
    if (a.size ()>b.size ())
        return 1;
    if (a.size ()<b.size ())
        return -1;
    if (a>b)
        return 1;
    if (a<b)
        return -1;
    return 0;
}

void getkey (node *&treap)
{
    if (treap==nil)
        return ;
    treap->key=treap->left->key+treap->right->key+1;
}

void rotleft (node *&treap)
{
    node *t;

    t=treap->left;
    treap->left=treap->right;
    t->right=treap;
    getkey (treap);
    getkey (t);
    treap=t;
}

void rotright (node *&treap)
{
    node *t;

    t=treap->right;
    treap->right=t->left;
    t->left=treap;
    getkey (treap);
    getkey (t);
    treap=t;
}


void insert (node *&treap,string s)
{
    if(treap==nil)
    {
        treap=new node;
        treap->str=s;
        treap->key=1;
        treap->priority=rand();
        treap->left=treap->right=nil;
    }
    else
    {
        if (cmp (s,treap->str)<0)
        {
            insert(treap->left,s);
            if (treap->left->priority>treap->priority)
                rotleft (treap);
        }
        else if (cmp(s,treap->str)>0)
        {
            insert(treap->right,s);
            if(treap->right->priority>treap->priority)
                rotright (treap);
        }
        getkey (treap);
    }
}

string find (node *treap,int k)
{
    if (treap==nil)
        return "";
    if (treap->left->key+1==k)
        return treap->str;
    if (treap->left->key+1>k)
        return find (treap->left,k);
    if (treap->left->key+1<k)
        return find (treap->right,k-(treap->left->key+1));
    return "";
}

int main ()
{
    int i,tip,x;
    string s;

    fin>>n;
    init ();
    for (i=1; i<=n; ++i)
    {
        fin>>tip;
        if (tip)
        {
            fin>>s;
            insert (rad,s);
        }
        else
        {
            fin>>x;
            fout<<find (rad,x)<<"\n";
        }
    }

    return 0;
}