Cod sursa(job #2633701)

Utilizator KlinashkaDiacicov Calin Marian Klinashka Data 8 iulie 2020 12:08:40
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
using namespace std;

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

struct trie {
    trie *kid[26];
    int finish, nr;
    trie() {
        nr=0;
        finish=0;
        for(int i=0;i<26;++i)
            kid[i]=0;
    }
};

void tinsert(trie *root, string s) {
    trie* curent=root;
    for(auto e:s) {
        int x=e-'a';
        if(!curent->kid[x])
            curent->kid[x]=new trie;
        ++curent->kid[x]->nr;
        curent=curent->kid[x];
    }
    ++curent->finish;
}

int tfind(trie *root, string s) {
    trie *curent=root;
    for(auto e:s) {
        int x=e-'a';
        if(!curent->kid[x])
            return 0;
        curent=curent->kid[x];
    }
    return curent->finish;
}

void tdelete(trie *nod, string s) {
    if(s.size()==0) {
        --nod->finish;
        return;
    }
    int x=s[0]-'a';
    tdelete(nod->kid[x], s.substr(1));
    --nod->kid[x]->nr;
    if(!nod->kid[x]->nr) {
        delete nod->kid[x];
        nod->kid[x]=0;
    }
}

int tlcp(trie *root, string s) {
    int sol=0;
    trie* curent=root;
    for(auto e:s) {
        int x=e-'a';
        if(!curent->kid[x])
            return sol;
        ++sol;
        curent=curent->kid[x];
    }
    return sol;
}

int main() {
    trie *root=new trie;
    int n, x;
    string s;
    while(fin>>x>>s) {
        if(x==0)
            tinsert(root, s);
        if(x==1)
            tdelete(root, s);
        if(x==2)
            fout<<tfind(root, s)<<'\n';
        if(x==3)
            fout<<tlcp(root, s)<<'\n';
    }
    return 0;
}