Cod sursa(job #1164404)

Utilizator SRaduRadu Szasz SRadu Data 2 aprilie 2014 01:03:35
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>

using namespace std;

struct TRIE {
    int cnt, nrFii;
    TRIE *Son[26];
    TRIE() {
        cnt = nrFii = 0;
        for(int i = 0; i < 26; i++)
            Son[i] = NULL;
    }
} *T;

int op;
string Word;

void Insert(TRIE *T, const string &S, int poz, int val) {
    if(poz == S.length()) {
        T->cnt += val;
        return;
    } 
    int ind = S[poz] - 'a';
    if(!T->Son[ind]) {
        T->Son[ind] = new TRIE;
        T->nrFii++;
    }
    Insert(T->Son[ind], S, poz + 1, val);
    if(!T->Son[ind]->cnt && !T->Son[ind]->nrFii) {
        delete T->Son[ind];
        T->Son[ind] = NULL;
        T->nrFii--;
    }
}

int Query(TRIE *T, const string &S, int poz) {
    if(poz == S.length()) {
        return T->cnt;
    }
    int ind = S[poz] - 'a';
    if(!T->Son[ind]) return 0;
    return Query(T->Son[ind], S, poz + 1);
}

int Prefix(TRIE *T, const string &S, int poz) {
    if(poz == S.length() || !T->Son[ S[poz] - 'a' ])
        return poz;
    return Prefix(T->Son[ S[poz] - 'a' ], S, poz + 1);
}

int main() {
    ifstream in("trie.in"); ofstream out("trie.out");
    T = new TRIE;
    while (in >> op >> Word) {
        switch(op) {
        case 0: 
            Insert(T, Word, 0, 1);
            break;
        case 1:
            Insert(T, Word, 0, -1);
            break;
        case 2:
            out << Query(T, Word, 0) << "\n";
            break;
        case 3:
            out << Prefix(T, Word, 0) << "\n";
            break;
        } 
    }
}