Cod sursa(job #319935)

Utilizator mihai_floreaFlorea Mihai Alexandru mihai_florea Data 2 iunie 2009 21:24:04
Problema Nums Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.17 kb
#include <fstream>
#include <string>
using namespace std;
const int LMAX=100005;
struct trie{
       int cnt;
       trie *cif[10];
       trie(){
         cnt=0;
         memset(cif,0,sizeof(cif));
         }
       ~trie();
       };
trie *T[LMAX];
int N,a[262144];
string nr;
ifstream fin("nums.in");
ofstream fout("nums2.out");
void Update(int n,int l,int r,int poz){
     if (l==r)
     {
        a[n]++;
        return;
     }
     int m=(l+r)/2;
     if (poz<=m) Update(2*n,l,m,poz);
            else Update(2*n+1,m+1,r,poz);
     a[n]=a[2*n]+a[2*n+1];
     }
void add(){
     int i,k,len=nr.length();
     if (!T[len]) T[len]=new trie;
     trie *t=T[len];
     for (i=0;i<len;++i)
     {
       k=nr[i]-'0';
       t->cnt++;  
       if (t->cif[k])
         t=t->cif[k];
       else
       {
         trie *p=new trie;
         t->cif[k]=p;
         t=p;
       }
     }
     t->cnt++;
     Update(1,1,LMAX,len);
     }
int search(){
     int i,k,len=nr.length();
     trie *t=T[len];
     if (!t) return 0;
     for (i=0;i<len;++i)
     {
         k=nr[i]-'0';
         if (t->cif[k])
           t=t->cif[k];
         else
           return 0;
     }
     return 1;
     }
int kth;
int Query(int n,int l,int r,int Sum){
     if (l==r)
     { 
        kth=Sum;
        return l;
     }
     int m=(l+r)/2;
     if (a[2*n]>=Sum) 
       return Query(2*n,l,m,Sum);
     else
       return Query(2*n+1,m+1,r,Sum-a[2*n]);
     }
string Sol;  
void findkth(int k){
     int i,c,len,count;
     len=Query(1,1,LMAX,k);
     trie *t=T[len];
     Sol.clear();
     for (i=0;i<len;++i)
     {
         count=0;
         for (c=0;c<=9;++c)
         {
           if (t->cif[c])
             count+=t->cif[c]->cnt;
           if (count>=kth) break;
         }
         Sol+=char('0'+c);
         t=t->cif[c];
         count-=t->cnt;
         kth-=count;
     }
     fout<<Sol<<'\n';    
     }
int main(){
    fin>>N;
    getline(fin,nr);
    while (N--){
       getline(fin,nr);
       int t=nr[0]-'0',k=0;
       nr.erase(0,2);
       if (t==1)
         if (!search()) add();
       if (t==0)
        {
         for (size_t i=0;i<nr.length();++i) k=k*10+nr[i]-'0';
         findkth(k);
        }
       }
    return 0;
}