Cod sursa(job #3165779)

Utilizator Horia_haivasHaivas Horia Horia_haivas Data 6 noiembrie 2023 21:53:41
Problema Trie Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 kb
/*
    "care a facut teste cu Lattice reduction attack e ciudat"
    "linistiti va putin"
    - 2023 -
*/
#include<bits/stdc++.h>
#define debug(x) cerr << #x << " " << x << "\n"
#define debugs(x) cerr << #x << " " << x << " "
#pragma GCC optimize("Ofast")

using namespace std;

struct Node
{
    int freq;
    int traffic;
    int muchii[27];
};

Node trie[100001];
int sz;

void ins(string s, int pos, int nodeidx)
{
    trie[nodeidx].traffic++;
    if (trie[nodeidx].muchii[s[pos]-'a'+1]==0)
    {
        sz++;
        trie[sz]={0,0,0};
        trie[nodeidx].muchii[s[pos]-'a'+1]=sz;
    }
    if (pos!=(s.size()))
    ins(s,pos+1,trie[nodeidx].muchii[s[pos]-'a'+1]);
    else
    trie[nodeidx].freq++;
}

void ers(string s, int pos, int nodeidx)
{
     trie[nodeidx].traffic--;
     if (pos!=(s.size()))
     ers(s,pos+1,trie[nodeidx].muchii[s[pos]-'a'+1]);
     else
     trie[nodeidx].freq--;
}

int ans;

void app(string s, int pos, int nodeidx)
{
    if (pos!=(s.size()) && trie[nodeidx].muchii[s[pos]-'a'+1]!=0)
    app(s,pos+1,trie[nodeidx].muchii[s[pos]-'a'+1]);
    else
    {
        if (trie[nodeidx].muchii[s[pos]-'a'+1]==0)
        ans=0;
        else
        ans=trie[nodeidx].freq;
        return;
    }
}

int lungime;

void lgpref(string s, int pos, int nodeidx)
{
    if (trie[nodeidx].traffic>=1)
    lungime++;
    else
    return;
    if (pos!=(s.size()) && trie[nodeidx].muchii[s[pos]-'a'+1]!=0)
    lgpref(s,pos+1,trie[nodeidx].muchii[s[pos]-'a'+1]);
    else
    return;
}

int main()
{
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int type;
    string s;
    sz=0;
    trie[0]={0,0,0};
    while (fin >> type  >> s)
    {
        if (type==0)
        {
            ins(s,0,0);
        }
        if (type==1)
        {
            ers(s,0,0);
        }
        if (type==2)
        {
            ans=0;
            app(s,0,0);
            fout << ans << "\n";
        }
        if (type==3)
        {
            lungime=-1;
            lgpref(s,0,0);
            fout << lungime << "\n";
        }
    }
}