Cod sursa(job #1217150)

Utilizator mikeshadowIon Complot mikeshadow Data 6 august 2014 19:04:55
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 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];
        bool chs [26];
        trie();
};

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

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

    t->x++;
    if (!t->chs[s[x]-'a'])
    {
        t->chs[s[x]-'a']=1;
        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->chs[s[x]-'a'] = 0;
    }
}

int rez=0;

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

    if (!t->chs[s[x]-'a'])
    {
        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->chs[s[x]-'a'])
    {
        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;
}