Cod sursa(job #1232752)

Utilizator Athena99Anghel Anca Athena99 Data 23 septembrie 2014 20:41:02
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <string>
#include <vector>

using namespace std;

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

const int sigma= 26;

struct str {
    int v[sigma], x, y;
};

string w;
vector <str> t;

void newnode(  ) {
    str x;
    x.x= x.y= 0;
    for ( int i= 0; i<sigma; ++i ) x.v[i]= 0;
    t.push_back(x);
}

void inserase( int p, int node, int add ) {
    if ( p==(int)w.size() ) t[node].x+= add, t[node].y+= add;
    else {
        if ( t[node].v[w[p]-'a']==0 ) {
            newnode();
            t[node].v[w[p]-'a']= (int)t.size()-1;
        }

        inserase( p+1, t[node].v[w[p]-'a'], add );
        t[node].y+= add;
    }
}

void query( int p, int node ) {
    if ( p==(int)w.size() ) fout<<t[node].x<<"\n";
    else if ( t[node].v[w[p]-'a']==0 ) fout<<"0\n";
    else query( p+1, t[node].v[w[p]-'a'] );
}

void query_prefix( int p, int node, int sol ) {
    if ( p==(int)w.size() || t[node].v[w[p]-'a']==0 || t[t[node].v[w[p]-'a']].y==0 ) fout<<sol<<"\n";
    else query_prefix( p+1, t[node].v[w[p]-'a'], sol+1 );
}

int main(  ) {
    newnode(); newnode();
    int c;
    for ( fin>>c>>w; !w.empty(); ) {
        if ( c==0 ) inserase(0, 1, 1);
        else if ( c==1 ) inserase(0, 1, -1);
        else if ( c==2 ) query(0, 1);
        else if ( c==3 ) query_prefix(0, 1, 0);

        w.clear();
        fin>>c>>w;
    }

    return 0;
}