Cod sursa(job #1881245)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 16 februarie 2017 12:01:14
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
using namespace std;

struct nod{
    int nr = 0, exact_nr = 0;
    nod* fii[26] = {}; };

void ins(nod *n, const string& str){
    ++n->nr;
    for(const auto x : str){
        if(!n->fii[x-'a']) n->fii[x-'a'] = new nod {};
        n = n->fii[x-'a'];
        ++n->nr; }
    ++n->exact_nr; }

void del(nod *n, const string& str){
    --n->nr;
    for(auto x : str)
        (n = n->fii[x-'a']),
        --n->nr;
    --n->exact_nr; }

int nr_ap(nod *n, const string& str){
    for(auto x : str){
        if(!n->fii[x-'a']) return 0;
        n = n->fii[x-'a']; }
    return n->exact_nr; }

int long_common_pref(nod *n, const string& str){
    int nr = 0;
    while(nr < str.size() && n->fii[str[nr]-'a'] && n->fii[str[nr]-'a']->nr)
        n = n->fii[str[nr++]-'a'];
    return nr; }

int main(){
    ifstream f("trie.in");
    ofstream g("trie.out");
    nod *rad = new nod {};
    int t;
    string str;
    while(f >> t){
        f >> str;
        if     (t == 0) ins(rad, str);
        else if(t == 1) del(rad, str);
        else if(t == 2) g << nr_ap(rad, str)            << '\n';
        else            g << long_common_pref(rad, str) << '\n'; }
    return 0; }