Cod sursa(job #1369785)

Utilizator tudorv96Tudor Varan tudorv96 Data 3 martie 2015 11:22:37
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>
#include <iostream>
using namespace std;

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

const int SIGMA = 26;

struct trie {
    int x;
    trie* f[SIGMA];
} *root = new trie;

void add(string s) {
    trie* crt = root;
    for (int i = 0; i < s.size(); ++i) {
        if (crt -> f[s[i] - 'a'] == NULL) {
            crt -> f[s[i] - 'a'] = new trie;
            crt -> f[s[i] - 'a'] -> x = 0;
            for (int j = 0; j < SIGMA; ++j)
                crt -> f[s[i] - 'a'] -> f[j] = NULL;
        }
        crt = crt -> f[s[i] - 'a'];
    }
    (crt -> x) ++;
}

void remove(int k, string &s, trie *crt) {
    if (k < s.size() - 1)
        remove(k + 1, s, crt -> f[s[k] - 'a']);
    crt -> f[s[k] - 'a'] -> x--;
    if (crt -> f[s[k] - 'a'] -> x == 0) {
        trie *aux = crt -> f[s[k] - 'a'];
        delete aux;
        crt -> f[s[k] -'a'] = NULL;
    }
}

int freq(string &s) {
    trie *crt = root;
    for (int i = 0; i < s.size(); ++i)
        if (crt -> f[s[i] - 'a'] != NULL)
            crt = crt -> f[s[i] - 'a'];
        else
            return 0;
    return crt -> x;
}

int pre(string &s) {
    trie *crt = root;
    for (int i = 0; i < s.size(); ++i)
        if (crt -> f[s[i] - 'a'] != NULL)
            crt = crt -> f[s[i] - 'a'];
        else
            return i;
    return s.size();
}

int main() {
    root -> x = 0;
    for (int i = 0; i < SIGMA; ++i)
        root -> f[i] = NULL;
    string s;
    int type;
    while (fin >> type >> s) {
        if (!type)
            add(s);
        if (type == 1)
            remove(0, s, root);
        if (type == 2)
            fout << freq(s) << "\n";
        if (type == 3)
            fout << pre(s) << "\n";
    }
}