Cod sursa(job #2924618)

Utilizator LuciBBadea Lucian LuciB Data 6 octombrie 2022 17:13:07
Problema Trie Scor 45
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
const int SIGMA = 26;

struct Node {
    Node* edges[SIGMA];
    int val, pref;
    Node() {
        val = pref = 0;
        for(int i = 0; i < SIGMA; i++)
            edges[i] = NULL;
    }
    inline Node* getEdge(char ch) {
        return edges[ch - 'a'];
    }
    inline Node* addEdge(char ch) {
        if(edges[ch - 'a'] == NULL)
            edges[ch - 'a'] = new Node();
        edges[ch - 'a']->pref++;
        return edges[ch - 'a'];
    }
    inline Node* deleteEdge(char ch) {
        edges[ch - 'a']->pref--;
        if(pref > 0)
            return edges[ch - 'a'];
        else {
            delete edges[ch - 'a'];
            return NULL;
        }
    }
};
Node* root;

void addWord(const char* word) {
    int i = 0;
    Node* node = root;
    while(word[i]) {
        node = node -> addEdge(word[i]);
        i++;
    }
    node -> val++;
}
void deleteWord(const char* word) {
    int i = 0;
    Node * node = root;
    while(word[i]) {
        node = node -> deleteEdge(word[i]);
        i++; 
    }
    node -> val--;
}

int frequence(const char* word) {
    int i = 0;
    Node* node = root;
    while(word[i] && node != NULL) {
        node = node -> getEdge(word[i]);
        i++;
    }
    if(node == NULL)
        return 0;
    else 
        return node -> val;
}

int prefix(const char* word) {
    int i = 0, len = 0;
    Node* node = root;
    while(word[i] && node != NULL && node -> pref != 0) {
        node = node -> getEdge(word[i]);
        i++;
        len++;
    }
    if(node == NULL || node -> pref == 0)
        len--;
    return len;
}

int main() {
    root = new Node();
    int op;
    char s[20];
    root -> pref = 1;
    while(fin >> op >> s) {
        switch(op) {
        case 0:
            addWord(s);
            break;
        case 1:
            deleteWord(s);
            break;
        case 2:
            fout << frequence(s) << endl;
            break;
        case 3:
            fout << prefix(s) << endl;
        }
    }
    return 0;
}