Cod sursa(job #3216000)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 15 martie 2024 15:39:26
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>
#define pii pair<int, int>
#define ff first
#define ss second
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define eb emplace_back


using namespace std;
const string TASK("trie");
ifstream fin(TASK + ".in");
ofstream fout(TASK + ".out");
#define cin fin
#define cout fout

const int N = 22;

int op;
char s[N];

struct node
{
    int cnt, end;
    node* sons[26];

    node()
    {
        cnt = 0;
        end = 0;
        for(int i = 0; i < 26; ++i)sons[i] = 0;
    }
};

node* t = new node;

void insert(node* x, char* s)
{
    x -> cnt ++;
    if(!s[0])
    {
        x -> end ++;
        return;
    }

    if(!x -> sons[s[0] - 'a'])x -> sons[s[0] - 'a'] = new node();

    insert(x -> sons[s[0] - 'a'], s + 1);
}

void erase(node* x, char* s)
{
    x -> cnt --;
    if(!s[0])
    {
        x -> end --;
        return;
    }

    erase(x -> sons[s[0] - 'a'], s + 1);
}

int count(node* x, char* s)
{
    if(!s[0])return x -> end;

    if(!x -> sons[s[0] - 'a'])return 0;

    return count(x -> sons[s[0] - 'a'], s + 1);
}

bool has_sons(node* x)
{
    for(int i = 0; i < 26; ++i)
        if(x -> sons[i])
            return true;
    return false;
}

int prefix(node* x, char* s, int dep = 0)
{
    if(!s[0])
    {
        if(x -> cnt)return dep;
        return 0;
    }

    int val = 0;
    if(x -> cnt)val = dep;

    if(!x -> sons[s[0] - 'a'])return val;

    return max(val, prefix(x -> sons[s[0] - 'a'], s + 1, dep + 1));
}

int main()
{
    while(cin >> op)
    {
        cin >> s;
        if(op == 0)insert(t, s);
        else if(op == 1)erase(t, s);
        else if(op == 2)cout << count(t, s) << '\n';
        else cout << prefix(t, s) << '\n';
    }
    return 0;
}