Cod sursa(job #2569723)

Utilizator ioana_marinescuMarinescu Ioana ioana_marinescu Data 4 martie 2020 13:22:17
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>

using namespace std;

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

const int SIGMA = 26;
const int MAX_L = 20;

class Node {
public:
    int nrap, nrc;
    Node* fii[SIGMA];

    Node() {
        for (int i = 0; i < SIGMA; i++)
            fii[i] = NULL;

        nrap = nrc = 0;
    }
};

Node* InsertTrie(Node *node, char *s) {
    if (node == NULL)
        node = new Node;

    node-> nrap++;

    if (s[0] == '\0')
        node-> nrc++;
    else
        node-> fii[s[0] - 'a'] = InsertTrie(node-> fii[s[0] - 'a'], s + 1);

    return node;
}

Node* DeleteTrie(Node *node, char *s) {
    node-> nrap--;

    if (s[0] == '\0')
        node-> nrc--;
    else
        node->fii[s[0] - 'a'] = DeleteTrie(node-> fii[s[0] - 'a'], s + 1);

    if (node-> nrap == 0)
        node = NULL;

    return node;

}

int NrCuv(Node *node, char *s) {
    if (node == NULL)
        return 0;

    if (s[0] == '\0')
        return node-> nrc;

    return NrCuv(node-> fii[s[0] - 'a'], s + 1);
}

int Prefix(Node *node, char *s) {
    if (node == NULL)
        return -1;

    if (s[0] == '\0')
        return 0;

    return 1 + Prefix(node-> fii[s[0] - 'a'], s + 1);
}

int main() {
    Node* trie = NULL;

    int op;
    char s[MAX_L + 5];

     while(fin >> op) {
        fin >> s;

        if(op == 0)
            trie = InsertTrie(trie, s);
        else if(op == 1)
            trie = DeleteTrie(trie, s);
        else if(op == 2)
            fout << NrCuv(trie, s) << '\n';
        else
            fout << Prefix(trie, s) << '\n';
    }

    return 0;
}