Cod sursa(job #3296961)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 19 mai 2025 16:19:54
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <bits/stdc++.h>

using namespace std;

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

const int lg=26;

struct trienode
{
    struct trienode *children[lg];
    int wordcnt;
    trienode()
    {
        wordcnt=0;
        for (int i=0; i<lg; i++)
            children[i]=NULL;
    }
};

trienode *root;

void insertw (trienode *root, string word)
{
    trienode *curr=root;
    for (auto c:word)
    {
        if (curr->children[c-'a']==NULL)
        {
            trienode *node=new trienode;
            curr->children[c-'a']=node;
        }
        curr=curr->children[c-'a'];
    }
    curr->wordcnt++;
}

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

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

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