Cod sursa(job #2966884)

Utilizator and_Turcu Andrei and_ Data 18 ianuarie 2023 17:14:57
Problema Trie Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <bits/stdc++.h>
#define Q ( S[i] - 'a' )
using namespace std;

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

struct nod_TRIE
{
    int is_last_leter,sons,ct;
    nod_TRIE *next_leter[26];
    nod_TRIE()
    {
        sons=is_last_leter=ct=0;
        for(int i=0;i<26;i++)
            next_leter[i]=0;
    }
};

nod_TRIE T;
nod_TRIE *root;

void Add_TRIE(string s,int i,nod_TRIE* x)
{
    int ch= s[i]-'a';
    x->ct++;
    if( i==s.size() )
    {
        x->is_last_leter++;
        return;
    }
    x->sons++;
    if( !x->next_leter[ch] )
    {
        x->next_leter[ch]= new nod_TRIE();
    }
    Add_TRIE(s,i+1,x->next_leter[ch]);
}

int Delete_TRIE(string S,int i,nod_TRIE*nod)
{
    if(i==S.length()) nod->is_last_leter--;
    else if( Delete_TRIE(S,i+1,nod->next_leter[Q]) )
    {
        nod->next_leter[Q] = 0;
        nod->sons --;
    }
    if( nod->is_last_leter == 0 && nod->sons == 0 && nod != root )
    {
        delete nod; return 1;
    }
    return 0;
}

//bool Delete_TRIE(string s,int i,nod_TRIE* x)
//{
///// 1 del
//    int ch= s[i]-'a';
//    if( i==s.size() )
//    {
//        x->ct--;
//        x->is_last_leter--;
//    }
//    else if( Delete_TRIE(s,i+1,x->next_leter[ch]) )
//    {
//        x->ct--;
//        x->sons--;
//        x->next_leter[ch]=0;
//    }
//    if( !x->sons and !x->is_last_leter and x!=root )
//    {
//        delete x;
//        return 1;
//    }
//    return 0;
//}

//int How_manny(string s,int i,nod_TRIE* x)
//{
//    if( i==s.size() )return x->is_last_leter;
//    int ch=s[i]-'a';
//    if( x->next_leter[ch] )
//        return How_manny( s,i+1,x->next_leter[ch] );
//    else return 0;
//}

int How_manny(string S,int i,nod_TRIE *nod)
{
    if(i==S.length()) return nod->is_last_leter;
    if(nod->next_leter[Q]) return How_manny(S,i+1,nod->next_leter[Q]);
    return 0;
}



int Longest_Prefix(string S,int i,nod_TRIE *nod,int k)
{
    if(i==S.length() || nod->next_leter[ S[i]-'a' ]==0) return k;
    return Longest_Prefix(S,i+1,nod->next_leter[ S[i]-'a' ],k+1);
}

int main()
{
    root= &T;
    int task;
    while(fin >> task)
    {
        string s;
        fin >> s;
        if( task==0 )
            Add_TRIE(s,0,root);
        if( task==1 )
            Delete_TRIE(s,0,root);
        if( task==2 )
            fout << How_manny(s,0,root) << "\n";
        if( task==3 )
            fout << Longest_Prefix(s,0,root,0) << "\n";
    }


    return 0;
}