Cod sursa(job #1336776)

Utilizator somuBanil Ardej somu Data 8 februarie 2015 09:08:43
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

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

struct Trie {
    int countWord; // de cate ori apare cuvantul i.e. de cate ori ajung in nodul curent
    int countSons; // cati fii are nodul curent (adica litere in lista de 26 de pozitii)
    Trie *son[27];
    Trie() {
        countWord = 0, countSons = 0;
        for (int i = 0; i < 27; i++)
            son[i] = NULL;
    }
};

Trie *root = new Trie; // tatal Trie-ului
string S;

void add(int pos, Trie *node) {
    if (pos == S.size()) {
        node->countWord++;
        return;
    }
    int letter = S[pos] - 'a';
    if (node->son[letter] == NULL) {
        node->son[letter] = new Trie();
        node->countSons++;
    }
    node = node->son[letter];
    add(pos+1, node);
}

bool del(int pos, Trie *node) {
    if (pos == S.size()) {
        node->countWord--;
    } else {
        if (del(pos+1, node->son[S[pos]-'a']) == 1) {
            node->son[S[pos]-'a'] = NULL;
            node->countSons--;
        }
    }
    if (node->countSons == 0 && node->countWord == 0 && node != root) {
        delete node;
        return 1;
    }
    return 0;
}

int nrOcc(int pos, Trie *node) {
    if (pos == S.size()) {
        return node->countWord;
    } else {
        int letter = S[pos] - 'a';
        if (node->son[letter] == NULL)
            return 0;
        else
            return nrOcc(pos+1, node->son[letter]);
    }
}

int lcp(int pos, Trie *node, int x) {
    if (pos == S.size() || node->son[S[pos]-'a'] == NULL)
        return x;
    else
        return lcp(pos+1, node->son[S[pos]-'a'], x+1);
}

int main() {
    
    for (;getline(fin, S);){
        switch (S[0]) {
            case '0':
                add(2, root);
                break;
            case '1':
                del(2, root);
                break;
            case '2':
                fout << nrOcc(2, root) << "\n";
                break;
            case '3':
                fout << lcp(2, root, 0) << "\n";
                break;
        }
    }
    
    fin.close();
    fout.close();
    
    return 0;
}