Cod sursa(job #2571526)

Utilizator 3DwArDPauliuc Edward 3DwArD Data 5 martie 2020 01:46:25
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.44 kb
#include <bits/stdc++.h>
using namespace std;

struct node{
    node() {}
    node(char nch){ ch = nch, number = 0, prefix = 0;}
    char ch;
    int number  = 0;
    int prefix = 0;
    vector <node*> next;
};

ifstream f("trie.in");
ofstream g("trie.out");
node * trie;
void add(node *current, string word, int i){
    current->prefix++;
    if(i==word.size()){
        current->number ++;
        return;
    }

    bool found = 0;
    int j=0;
    while(j<current->next.size() && !found){
        if(current->next[j]->ch == word[i])
            found =  true;
        else
            j++;
    }
    if(!found){
        current->next.push_back(new node(word[i]));
    }

    add(current->next[j], word, i+1);
}
void del(node *current, string word, int i){
    current->prefix--;
    if(i==word.size()){
        current->number --;
        return;
    }

    bool found = 0;
    int j=0;

    while(j<current->next.size() && !found){
        if(current->next[j]->ch == word[i])
            found =  true;
        else
            j++;
    }

    del(current->next[j], word, i+1);
}

void aparitii(string word, node * current = trie, int i = 0){
    if(i==word.size()){
        g<<current->number<<'\n';
        return;
    }

    bool found = 0;
    int j=0;

    while(j<current->next.size() && !found){
        if(current->next[j]->ch == word[i])
            found =  true;
        else
            j++;
    }
    if(found == false){
        g<<"0\n";
        return;
    }
    aparitii(word, current->next[j], i+1);
}
void prefix(string word, node * current = trie, int i = 0){
    if(i==word.size()){
        g<<i<<'\n';
        return;
    }

    bool found = 0;
    int j=0;

    while(j<current->next.size() && !found){
        if(current->next[j]->ch == word[i] && current->next[j]->prefix)
            found =  true;
        else
            j++;
    }
    if(found == false){
        g<<i<<'\n';
        return;
    }
    prefix(word, current->next[j], i+1);
}
int main()
{
    int op;
    string word;
    trie= new node();
    while(f>> op >> word){
        switch(op){
        case 0:
            add(trie, word, 0);
            break;
        case 1:
            del(trie, word, 0);
            break;
        case 2:
            aparitii(word);
            break;
        case 3:
            prefix(word);
            break;
        }
    }
    return 0;
}