Cod sursa(job #2571511)

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

struct node{
    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){
        node newNode;
        newNode.ch = word[i];
        current.next.push_back(newNode);
    }

    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;
    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;
}