Cod sursa(job #3303742)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 17 iulie 2025 15:55:27
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");

const int lg=26;

struct trie
{
    struct trie *children[lg];
    int cnt, endw;
    trie()
    {
        cnt=endw=0;
        for (int i=0; i<lg; i++)
            children[i]=NULL;
    }
};

trie *root;

void insert_word (trie *root, string word)
{
    trie *curr=root;
    for (auto c:word)
    {
        int key=c-'a';
        if (curr->children[key]==NULL)
            curr->children[key]=new trie();
        curr=curr->children[key];
        curr->cnt++;
    }
    curr->endw++;
}

void delete_word (trie *root, string word)
{
    trie *curr=root;
    for (auto c:word)
    {
        int key=c-'a';
        curr=curr->children[key];
        curr->cnt--;
    }
    curr->endw--;
}

int frecv (trie *root, string word)
{
    trie *curr=root;
    for (auto c:word)
    {
        int key=c-'a';
        if (curr->children[key]==NULL)
            return 0;
        curr=curr->children[key];
    }
    return curr->endw;
}

int pref (trie *root, string word)
{
    trie *curr=root;
    int rez=0;
    for (auto c:word)
    {
        int key=c-'a';
        if (curr->children[key]==NULL || curr->children[key]->cnt==0)
            return rez;
        rez++;
        curr=curr->children[key];
    }
    return rez;
}

int main()
{
    root=new trie();
    int cer;
    while (fin >> cer)
    {
        string s;
        fin >> s;
        if (cer==0)
            insert_word(root,s);
        if (cer==1)
            delete_word(root,s);
        if (cer==2)
            fout << frecv(root,s) << '\n';
        if (cer==3)
            fout << pref(root,s) << '\n';
    }
    return 0;
}