Cod sursa(job #2546892)

Utilizator ioana_marinescuMarinescu Ioana ioana_marinescu Data 14 februarie 2020 18:20:55
Problema Trie Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>

const int SIGMA = 26;

using namespace std;

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

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

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

        nrap = nrc = 0;
    }
};

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

    node-> nrap++;

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

    return node;
}

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

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

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

    return node;
}

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

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

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

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

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

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

}
int main() {
    Node *trie = NULL;
    char s[21];
    int op;

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

        if (op == 0)
            trie = insert_trie(trie, s);
        if (op == 1)
            trie = delete_trie(trie, s);
        if (op == 2)
            fout << ap(trie, s) << '\n';
        if (op == 3)
            fout << prefix(trie, s) << '\n';
    }

    return 0;
}