Cod sursa(job #2653204)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 27 septembrie 2020 12:50:44
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <bits/stdc++.h>

using namespace std;

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

const int SIGMA = 26;

struct TrieNode {
    TrieNode() {
        words = sons = 0;
        memset(son, 0, sizeof son);
    }
    int words, sons;
    TrieNode* son[SIGMA];
};

TrieNode* root = new TrieNode;
char a[SIGMA];

void insertWord(TrieNode* nod, char* word) {
    if (*word == '\0') {
        nod->words++;
        return;
    }

    if (nod->son[*word - 'a'] == 0) {
        nod->son[*word - 'a'] = new TrieNode;
        nod->sons++;
    }
    insertWord(nod->son[*word - 'a'], word + 1);
}

bool deleteWord(TrieNode* nod, char* word) {
    if (*word == '\0') {
        nod->words--;
    }
    else {
        bool deletedNode = deleteWord(nod->son[*word - 'a'], word + 1);
        if (deletedNode) {
            nod->son[*word - 'a'] = 0;
            nod->sons--;
        }
    }

    if (nod->words == 0 && nod->sons == 0 && nod != root) {
        delete nod;
        return true;
    }
    return false;
}

int countOccurences(TrieNode* nod, char* word) {
    if (*word == '\0') {
        return nod->words;
    }

    if (nod->son[*word - 'a'])
        return countOccurences(nod->son[*word - 'a'], word + 1);
    return 0;
}

int computePrefixLength(TrieNode* nod, char* word, int prefixLength) {
    if (*word == '\0' || nod->son[*word - 'a'] == 0)
        return prefixLength;
    return computePrefixLength(nod->son[*word - 'a'], word + 1, prefixLength + 1);
}

int main()
{
    while (fin.getline(a, SIGMA)) {
        switch (a[0]) {
            case '0': insertWord(root, a + 2); break;
            case '1': deleteWord(root, a + 2); break;
            case '2': fout << countOccurences(root, a + 2) << '\n'; break;
            case '3': fout << computePrefixLength(root, a + 2, 0) << '\n'; break;
        }
    }
    return 0;
}