Cod sursa(job #2805804)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 21 noiembrie 2021 23:36:46
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>
using namespace std;

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

struct nod{
    nod *fiu[26];
    int end_of;
    int sons;
    nod() {
        memset(fiu,0,sizeof(fiu));
        end_of=0;
        sons=0;
    }
};

nod* root=new nod;
int c;
string word;

void add(nod *parent,int pos) {
    if (pos==word.size()) {
        parent->end_of++;
        return;
    }
    if (parent->fiu[word[pos]-'a']==0) {
        parent->fiu[word[pos]-'a'] = new nod;
        parent->sons++;
    }
    add(parent->fiu[word[pos]-'a'],pos+1);
}

bool pop(nod *parent,int pos) {
    if (pos==word.size()) {
        parent->end_of--;
    }
    else {
        if (pop(parent->fiu[word[pos]-'a'],pos+1)) {
            parent->fiu[word[pos]-'a']=0;
            parent->sons--;
        }
    }
    if (parent->end_of==0 && parent->sons==0 && parent!=root) {
        delete parent;
        return true;
    }
    return false;
}

int count_words(nod *parent,int pos) {
    if (pos==word.size()) {
        return parent->end_of;
    }
    if (parent->fiu[word[pos]-'a']==0) {
        return 0;
    }
    return count_words(parent->fiu[word[pos]-'a'],pos+1);
}

int common_prefix(nod *parent,int pos) {
    if (pos==word.size()) {
        return pos;
    }
    if (parent->fiu[word[pos]-'a']==0) {
        return pos;
    }
    return common_prefix(parent->fiu[word[pos]-'a'],pos+1);
}

int main()
{
    while (f>>c) {
        f >>word;
        if (c==0) {
            add(root,0);
        }
        else if (c==1) {
            pop(root,0);
        }
        else if (c==2) {
           g <<count_words(root,0) <<"\n";
        }
        else {
         g << common_prefix(root,0) <<"\n";
        }
    }
    return 0;
}