Cod sursa(job #883082)

Utilizator MagnvsDaniel Constantin Anghel Magnvs Data 19 februarie 2013 18:33:26
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#include <vector>

using namespace std;

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

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

struct tn{
    int v[sigma];
    int d, dp;
    tn(){
        for (int i= 0; i<sigma; ++i){
            v[i]= -1;
        }
        d= 0; dp= 0;
    }
};
vector <tn> tr;

char ch[lmax+4];

void tr_ins(int x, int i){
    if (ch[i]==0){
        ++tr[x].d;
    }else{
        if (tr[x].v[ch[i]-'a']==-1){
            tr[x].v[ch[i]-'a']= tr.size();
            tr.push_back(tn());
        }
        tr_ins(tr[x].v[ch[i]-'a'], i+1);
    }
    ++tr[x].dp;
}

int tr_del(int x, int i){
    if (ch[i]==0){
        --tr[x].d;
    }else{
        if (tr_del(tr[x].v[ch[i]-'a'], i+1)){
            tr[x].v[ch[i]-'a']= -1;
        }
    }
    --tr[x].dp;
    if (tr[x].dp==0){
        return 1;
    }else{
        return 0;
    }
}

int tr_que(int x, int i){
    if (ch[i]==0){
        return tr[x].d; 
    }else if (tr[x].v[ch[i]-'a']!=-1){
        return tr_que(tr[x].v[ch[i]-'a'], i+1);
    }else{
        return 0;
    }
}

int tr_que_pre(int x, int i, int k){
    if (ch[i]==0){
        return k; 
    }else if (tr[x].v[ch[i]-'a']!=-1){
        return tr_que_pre(tr[x].v[ch[i]-'a'], i+1, k+1);
    }else{
        return k;
    }
}

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

    return 0;
}