Cod sursa(job #3298008)

Utilizator Luca_georgescuLucageorgescu Luca_georgescu Data 25 mai 2025 20:41:07
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

struct trie {

    trie* child[26];
    int cnt;
    int pass;

    trie()
    {
        cnt=pass=0;
        for (int j=0; j<26; j++)
            child[j]=0;
    }
};

trie* root=new trie;

void add(string s)
{
    trie* curr=root;

    for (char c:s )
    {
        int i=c-'a';

        if ( !curr->child[i] )
        {
            trie* p=new trie;
            curr->child[i]=p;
        }
        curr=curr->child[i];
        curr->pass++;
    }

    curr->cnt++;
}

void sterge(string s)
{
    trie* curr=root;

    // parent index copil
    vector < pair<trie*,int> > path;

    for (char c : s)
    {
        int i=c-'a';
        path.push_back({curr,i});
        trie* next=curr->child[i];

        if ( !next )
            return;

        next->pass--;
        curr=next;
    }

    curr->cnt--;

    for (int k=path.size()-1; k>=0; k-- )
    {
        trie* parent=path[k].first;
        int idx=path[k].second;
        trie* node=parent->child[idx];

        if ( node->cnt==0 && node->pass==0 )
        {
            delete node;
            parent->child[idx]=0;
        }
        else break;
    }
}

int numara(string s)
{
    trie* curr=root;
    for (char c:s )
    {
        int i=c-'a';
        if ( curr->child[i]==0 )
            return 0;
        curr=curr->child[i];
    }
    return curr->cnt;
}

int prefix(string s)
{
    trie *curr=root;
    int lg=0;

    for (char c:s )
    {
        int i=c-'a';

        if ( curr->child[i]==0 )
            break;

        curr=curr->child[i];

        if ( curr->pass>0 )
            lg++;
        else break;
    }
    return lg;
}

int main()
{
    int c;
    string s;

    while ( f >> c >> s )
    {
        if ( c==0 )
            add(s);
        else if ( c==1 )
            sterge(s);
        else if ( c==2 )
            g << numara(s) << '\n';
        else if ( c==3 )
            g << prefix(s) << '\n';
    }

    return 0;
}