Cod sursa(job #2848030)

Utilizator razvanalexrotaruRazvan Alexandru Rotaru razvanalexrotaru Data 12 februarie 2022 01:12:50
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");
struct Node
{
    int cnt = 0;
    int lvs = 0;
    int next[26] = {};
};
vector<Node>trie{1};
void insert(string& str)
{
    int node=0;
    for(char chr:str)
    {
        if(!trie[node].next[chr-'a'])
        {
            trie[node].next[chr-'a']=trie.size();
            Node k;
            trie.push_back(k);
        }
        node=trie[node].next[chr-'a'];
        trie[node].lvs++;
    }
    trie[node].cnt++;
}
void erase(string& str)
{
    int node=0;
    for(char chr:str)
    {
        node=trie[node].next[chr-'a'];
        trie[node].lvs--;
    }
    trie[node].cnt--;
    node=0;
    for(char chr:str)
    {
        if(!trie[trie[node].next[chr - 'a']].lvs)
        {
            trie[node].next[chr-'a']=0;
            return;
        }
        node=trie[node].next[chr-'a'];
    }
}
int count(string& str)
{
    int node=0;
    for (char chr:str)
    {
        if (!trie[node].next[chr-'a'])
            return 0;
        node=trie[node].next[chr-'a'];
    }
    return trie[node].cnt;
}
int lcp(string& str)
{
        int node=0,len=0;
        for(char chr:str)
        {
            if(!trie[node].next[chr-'a'])
                return len;
            node=trie[node].next[chr-'a'];
            len++;
        }
        return len;
}
int main()
{
    int type;
    string str;
    while(fin>>type>>str)
        if(type==0)
            insert(str);
            else
            if(type==1)
                erase(str);
                else
                    if (type == 2)
            fout<<count(str)<<'\n';
        else
            fout<<lcp(str)<<'\n';
    return 0;
}