Cod sursa(job #1458415)

Utilizator greenadexIulia Harasim greenadex Data 7 iulie 2015 14:53:08
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>

using namespace std;

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

int op;
string word;

struct nod {
    nod* f[26];
    int cnt, pre;

    nod() {
        memset(f, 0, sizeof(f));
        cnt = pre = 0;
    }
};

nod* root = new nod();

void add(nod* t, int poz, string& s){
    if (poz == s.size()){
        t -> cnt++;
        return;
    }
    int lit = s[poz] - 'a';

    if (t -> f[lit] == NULL)
        t -> f[lit] = new nod;

    t -> f[lit] -> pre++;
    add(t -> f[lit], poz + 1, s);
}

void del(nod* t, int poz, string& s){
    if (poz == s.size()){
        t -> cnt--;
        return;
    }
    int lit = s[poz] - 'a';
    t -> f[lit] -> pre--;
    del(t -> f[lit], poz + 1, s);
}

int out(nod* t, int poz, string& s){
    if (poz == s.size())
        return t -> cnt;
    int lit = s[poz] - 'a';
    if (t -> f[lit] == NULL)
        return 0;
    return out(t -> f[lit], poz + 1, s);
}

int prefixe(nod* t, int poz, string& s){
    if(poz == s.size())
        return poz;
    int lit = s[poz] - 'a';
    if (t -> f[lit] == NULL || t -> f[lit] -> pre == 0)
        return poz;
    return prefixe(t -> f[lit], poz + 1, s);
}

int main() {
    while (fin >> op >> word)
        switch(op){
        case 0:
            add(root, 0, word);
            break;
        case 1:
            del(root, 0, word);
            break;
        case 2:
            fout << out(root, 0, word) << '\n';
            break;
        case 3:
            fout << prefixe(root, 0, word) << '\n';
            break;
        }
    return 0;
}