Cod sursa(job #831344)

Utilizator MagnvsDaniel Constantin Anghel Magnvs Data 8 decembrie 2012 15:01:56
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 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, dp;

    tn(){
        for (int i= 0; i<sigma; ++i){
            son[i]= 0;
        }
        d= 0; dp= 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->son[*s-'a']= new tn;
        }
        tr_ins(x->son[*s-'a'], s+1);
    }
    ++x->dp;
}

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

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&& x->son[*s-'a']->dp>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;
}