Cod sursa(job #2289560)

Utilizator FlaviusFeteanFetean Flavius FlaviusFetean Data 24 noiembrie 2018 20:25:06
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>

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

struct node{
short unsigned int ctW = 0;
int ct = 1;
node* v[26] = {NULL};
} root;

void word_in(char w[])
{
    node* x = &root, *newNode;
    int i = 0, r;
    while(w[i] != '\0'){
        r = w[i] - 97;
        if(x->v[r] != NULL) x = x->v[r], x->ct++;
        else{
            newNode = new node;
            x->v[r] = newNode; x = newNode;
        } i++;
    }
    x->ctW++;
}

void word_out(char w[])
{
    node* x = &root, *aux;
    int i = 0, r;
    while(w[i] != '\0'){
        r = w[i] - 97;x->v[r]->ct--;
        aux = x->v[r];
        if(x->v[r]->ct == 0) x->v[r] = NULL;
        if(x->ct == 0) delete x;
        x = aux; i++;
    }
    x->ctW--;
    if(x->ct == 0) delete x;
}

int nr_app(char w[])
{
    node* x = &root, *aux;
    int i = 0, r;
    while(w[i] != '\0'){
        r = w[i] - 97;i++;
        if(x->v[r] != NULL) x = x->v[r];
        else return 0;
    }
    return x->ctW;
}

int longestCommonPrefix(char w[])
{
    node* x = &root, *aux;
    int i = 0, r, ct = 0;
    while(w[i] != '\0'){
        r = w[i] - 97;i++;
        if(x->v[r] != NULL) x = x->v[r];
        else break;
        if(x->ct > 0) ct++;
        else break;
    }
    return ct;
}

int main()
{
    int t;
    char w[25];
    fin >> t;fin >> w;
    while(!fin.eof()){
        switch(t){
            case 0: word_in(w); break;
            case 1: word_out(w); break;
            case 2: fout << nr_app(w) << "\n"; break;
            case 3: fout << longestCommonPrefix(w) << "\n"; break;
        }
        fin >> t; fin >> w;
    }
    return 0;
}