Cod sursa(job #3242646)

Utilizator BucsMateMate Bucs BucsMate Data 12 septembrie 2024 21:51:12
Problema Trie Scor 45
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

ifstream input("trie.in");
ofstream output("trie.out");

struct Node
{
    int nr = 0;
    Node *next[26] = {};
};

void add(Node *root, string str)
{
    Node *akt = root;
    for(int i = 0; str[i] != '\0'; i++){
        if(akt->next[str[i]-'a'] == nullptr){
            akt->next[str[i]-'a'] = new Node;
        }
        akt = akt->next[str[i]-'a'];
    }
    akt->nr++;
}

void del(Node *root, string str)
{
    Node *akt = root;
    vector<Node *> nodes(25);
    nodes[0] = root;
    for(int i = 0; str[i] != '\0'; i++){
        akt = akt->next[str[i]-'a'];
        nodes[i+1] = akt;
    }
    akt->nr--;
    for(int i = str.size(); i > 0; i--){
        bool has_next = false;
        for(int j = 0; j <= 25; j++){
            if(nodes[i]->next[j] != nullptr){
                has_next = true;
            }
        }
        if(has_next || nodes[i]->nr > 0){
            break;
        }
        else{
            nodes[i-1]->next[str[i-1]-'a'] = nullptr;
            delete akt;
        }
    }
}

int count_appearances(Node *root, string str)
{
    Node *akt = root;
    for(int i = 0; str[i] != '\0'; i++){
        if(akt->next[str[i]-'a'] == nullptr){
            return 0;
        }
        akt = akt->next[str[i]-'a'];
    }
    return akt->nr;
}

int longest_prefix(Node *root, string str)
{
    int num = 0;
    Node *akt = root;
    for(int i = 0; str[i] != '\0'; i++){
        if(akt->next[str[i]-'a'] == nullptr){
            break;
        }
        akt = akt->next[str[i]-'a'];
        num++;
    }
    return num;
}

int main()
{
    Node *root = new Node;
    int a;
    string str;
    while(input >> a >> str){
        switch(a){
            case 0:
                add(root, str);
                break;
            case 1:
                del(root, str);
                break;
            case 2:
                output << count_appearances(root, str) << endl;
                break;
            case 3:
                output << longest_prefix(root, str) << endl;
                break;
        }
    }
    return 0;
}