Cod sursa(job #2198136)

Utilizator SqueekDanielTodasca Daniel SqueekDaniel Data 23 aprilie 2018 18:29:28
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.17 kb
#include <bits/stdc++.h>
#define nchar 'z'-'a'+1

std::ifstream f("trie.in");
std::ofstream g("trie.out");

typedef void (*func_ptr)();
func_ptr func[4];               //why not

struct trie {
    int nson, cnt;
    trie *son[nchar];

    trie() {
        this->nson = this->cnt = 0;
        for (int i=0; i<nchar; i++)
            this->son[i] = 0;
    }
};
trie *data = new trie;

void insert_to_trie(char str[], trie *nod = data) {
    if(isalpha(str[0])) {
        char ch = str[0] - 'a';
        if(nod->son[ch])
            insert_to_trie(str+1, nod->son[ch]);
        else {
            nod->son[ch] = new trie;
            nod->nson++;
            insert_to_trie(str+1, nod->son[ch]);
        }
    }
    else
        nod->cnt++;
}
bool remove_from_trie(char str[], trie *nod = data) {
    if(isalpha(str[0])) {
        char ch = str[0] - 'a';
        if(remove_from_trie(str+1, nod->son[ch])) {
            nod->son[ch] = 0;
            nod->nson--;
        }
    }
    else
        nod->cnt--;

    if(nod->cnt == 0 && nod->nson == 0 && nod != data) {
        delete nod;
        return true;
    } return false;
}
trie* get(char str[], trie *nod = data) {
    if(isalpha(str[0])) {
        char ch = str[0] - 'a';
        if(nod->son[ch])
            return get(str+1, nod->son[ch]);
        else return 0;
    }
    else return nod;
}
int prefix_len(char str[], trie *nod = data) {
    if(!isalpha(str[0])) return 0;
    char ch = str[0] - 'a';

    if(nod->son[ch])  return 1 + prefix_len(str+1, nod->son[ch]);
    return 0;
}

void query0() {
    char cuv[25]; f >> cuv;
    insert_to_trie(cuv, data);
}
void query1() {
    char cuv[25]; f >> cuv;
    remove_from_trie(cuv);
}
void query2() {
    char cuv[25]; f >> cuv;
    trie *nod = get(cuv);
    if(nod) g << nod->cnt << "\n" ;
    else g << 0 << "\n" ;
}
void query3() {
    char cuv[25]; f >> cuv;
    g << prefix_len(cuv) << "\n";
}

void rezolvare() {
    func[0] = &query0;
    func[1] = &query1;
    func[2] = &query2;
    func[3] = &query3;

    int tip;
    while(f >> tip)
        func[tip]();
}

int main()
{
    rezolvare();

    return 0;
}