Cod sursa(job #1218444)

Utilizator tdr_drtTdr Drt tdr_drt Data 11 august 2014 10:49:15
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <fstream>
#include <map>
#include <string.h>
#include <string>
#include <algorithm>

using namespace std;

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

string s;
int n;

class trie
{
    public:
        int x,y;
        trie* ch[26];
        trie();
};

trie::trie()
{
    x=0;
    y=0;
    memset(ch,0,sizeof(ch));
}

void add (int x, trie *t)
{
    if (x==n) { t->x++; t->y++; return;}

    t->x++;
    if (t->ch[s[x]-'a']==NULL)
    {
        t->ch[s[x]-'a'] = new trie();
    }

    add(x+1,t->ch[s[x]-'a']);
}

void del(int x, trie *t)
{
    if (x==n) { t->x--; t->y--; return;}

    t->x--;

    del(x+1,t->ch[s[x]-'a']);

    if ((t->ch[s[x]-'a'])->x==0)
    {
        t->ch[s[x]-'a'] = NULL;
    }
}

int rez=0;

void counter(int x, trie *t)
{
    if (x==n) {rez = t->y; return;}

    if (t->ch[s[x]-'a']==NULL)
    {
        rez=0;
        return;
    } else counter(x+1,t->ch[s[x]-'a']);
}

void prefix(int x, trie *t)
{
    if (x==n) {rez = n; return;}

    if (t->ch[s[x]-'a']==NULL)
    {
        rez=x;
        return;
    } else prefix(x+1,t->ch[s[x]-'a']);
}

trie *root;

int main()
{
    root = new trie();
    while (!fin.eof())
    {
        int x=-1;
        fin>>x;
        fin>>s;
        n = s.length();
        if (x==-1) break;
        if (x==0)
        {
            add(0,root);
        } else if (x==1)
        {
            del(0,root);
        } else if (x==2)
        {
            counter(0,root);
            fout<<rez<<'\n';
        } else
        {
            prefix(0,root);
            fout<<rez<<'\n';
        }
    }
    return 0;
}