Cod sursa(job #1369943)

Utilizator tudorv96Tudor Varan tudorv96 Data 3 martie 2015 12:21:22
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 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(string &s) {
    trie *crt = root;
    int i;
    for (i = 0; i < s.size() - 1; ++i)
        crt = crt -> f[s[i] - 'a'];
    crt -> f[s[i] - 'a'] -> x --;
    if (!(crt -> f[s[i] - 'a'] -> x)) {
        trie *p = crt -> f[s[i] - 'a'];
        delete p;
        crt -> f[s[i] - '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(s);
        //if (type == 2)
            //fout << freq(s) << "\n";
        //if (type == 3)
            //fout << pre(s) << "\n";
    }
}