Cod sursa(job #2636774)

Utilizator eu3neuomManghiuc Teodor-Florin eu3neuom Data 19 iulie 2020 20:32:04
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <bits/stdc++.h>

using namespace std;

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

const int len = 26;
struct Node {
    int cnt, childs;
    Node* next[len];
    
    Node() {
        cnt = 0;
        childs = 0;
        for (int i = 0; i < len; ++i) {
            next[i] = NULL;
        }
    }
};

Node *root = new Node;

void Insert(string s) {
    Node *node = root;
    for (auto ch : s) {
        node -> childs += 1;
        
        int norm = ch - 'a';
        if (node -> next[norm] == NULL) {
            node -> next[norm] = new Node;
        }
        node = node -> next[norm];
    }   
    node -> childs += 1;
    node -> cnt += 1;
}

void Print(string s) {
    Node *node = root;
    for (auto ch : s) {
        int norm = ch - 'a';
        if (node -> next[norm] == NULL) {
            fout << "0\n";
            return;
        }
        node = node -> next[norm];
    }  
    fout << node -> cnt << "\n";
}

bool Delete(Node *node, string s, int idx) {
    node -> childs -= 1;
    if (idx < (int)s.size()) {
        int norm = s[idx] - 'a';
        if (Delete(node -> next[norm], s, idx + 1)) {
            node -> next[norm] = NULL;
        }
    } else {
        node -> cnt -= 1;
    }
    
    if (node -> childs == 0 && node != root) {
        delete node;
        return true;
    } 
    return false;
}

void Common(string s) {
    int ans = 0;
    Node *node = root;
    for (auto ch : s) {
        int norm = ch - 'a';
        if (node -> next[norm] == NULL) {
            fout << ans << "\n";
            return;
        }
        ans += 1;
        node = node -> next[norm];
    }  
    fout << ans << "\n";
}

int main() {
    int op;
    string s;
    
    while (fin >> op >> s) {
        if (op == 0) {
            Insert(s);
        } else if (op == 1) {
            Delete(root, s, 0);
        } else if (op == 2) {
            Print(s);
        } else {
            Common(s);
        }
    }
    return 0;
}