Cod sursa(job #1217145)

Utilizator mikeshadowIon Complot mikeshadow Data 6 august 2014 19:00:36
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>

using namespace std;

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

string s;
int n;

class trie
{
    public:
        int x,y;
        map<char,trie*> ch;
        map<char,int> chs;
        trie();
};

trie::trie()
{
    x=0;
}

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

    t->x++;
    if (!t->chs[s[x]])
    {
        t->chs[s[x]]=1;
        t->ch[s[x]] = new trie();
    }

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

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

    t->x--;

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

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

int rez=0;

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

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

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

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

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;
}