Cod sursa(job #831345)

Utilizator MagnvsDaniel Constantin Anghel Magnvs Data 8 decembrie 2012 15:04:30
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <cassert>

using namespace std;

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

const int sigma= 26;
const int lmax= 20;

struct tn{
    tn *son[sigma];
    int d, ns;

    tn(){
        for (int i= 0; i<sigma; ++i){
            son[i]= 0;
        }
        d= 0; ns= 0;
    }
};

tn *tr= new tn;

char ch[lmax+4];

void tr_ins(tn *x, char *s){
    if (*s==0){
        ++x->d;
    }else{
        if (x->son[*s-'a']==0){
            ++x->ns;
            x->son[*s-'a']= new tn;
        }
        tr_ins(x->son[*s-'a'], s+1);
    }
}

int tr_del(tn *x, char *s){
    if (*s==0){
        --x->d;
    }else{
        if (tr_del(x->son[*s-'a'], s+1)){
            x->son[*s-'a']= 0;      
            --x->ns;
        }
    }
    if (x->ns==0&& x->d==0&& x!=tr){
        delete x;
        return 1;
    }else{
        return 0;
    }
}

int tr_q(tn *x, char *s){
    if (*s==0){
        return x->d;
    }else if (x->son[*s-'a']!=0){
        return tr_q(x->son[*s-'a'], s+1);
    }else{
        return 0;
    }
}

int tr_qp(tn *x, char *s, int k){
    if (*s==0){
        return k;
    }else if (x->son[*s-'a']!=0){
        return tr_qp(x->son[*s-'a'], s+1, k+1);
    }else{
        return k;
    }
}

int main(){
    while (!fin.getline(ch, lmax+4).eof()){
        if (ch[0]=='0'){
            tr_ins(tr, ch+2);
        }else if (ch[0]=='1'){
            tr_del(tr, ch+2);
        }else if (ch[0]=='2'){
            fout<<tr_q(tr, ch+2)<<"\n";
        }else{
            fout<<tr_qp(tr, ch+2, 0)<<"\n";
        }
    }
    return 0;
}