Cod sursa(job #2575747)

Utilizator racheriunicolaechowchow racheriunicolae Data 6 martie 2020 15:14:36
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>

using namespace std;

struct trie
{
    int cuv , nr;
    trie *nxt[30];
    trie()
    {
        nr = cuv = 0;
        for(int i = 0; i <= 26; i++)nxt[i] = NULL;
    }
};

void adauga(trie *t , string s , int pos)
{
    if(pos == s.size())
    {
        t -> cuv++;
        t -> nr++;
        return;
    }
    t -> nr++;
    char lit = s[pos];
    if(t -> nxt[lit - 'a'] == NULL)
    {
        trie *urm = new trie();
        t -> nxt[lit - 'a'] = urm;
    }
    adauga(t -> nxt[lit - 'a'] , s , pos + 1);
}

void sterge(trie *t , string s , int pos)
{
    if(pos == s.size())
    {
        t -> nr--;
        t -> cuv--;
        return;
    }
    t -> nr--;
    char lit = s[pos];
    if(t -> nxt[lit - 'a'] == NULL)return;
    sterge(t -> nxt[lit - 'a'] , s , pos + 1);
}

int aparitii(trie *t , string s , int pos)
{
    if(pos == s.size())
        return (t -> cuv) ;

    char lit = s[pos];
    if(t -> nxt[lit - 'a'] != NULL) return aparitii(t -> nxt[lit - 'a'] , s , pos + 1);
    return 0;
}

void pre(trie *t , string s , int pos , int &ans)
{
    if(t -> nr != 0)ans = max(ans , pos);
    if(pos == s.size())
        return;


    char lit = s[pos];
    if(t -> nxt[lit - 'a'] != NULL)pre(t -> nxt[lit - 'a'] , s , pos + 1 , ans);
}
int op;
string w;
int main()
{
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    trie *p = new trie();
    while(fin >> op >> w)
    {
        if(op == 0) adauga(p , w , 0);
        if(op == 1) sterge(p , w , 0);
        if(op == 2) fout << aparitii(p , w , 0) << "\n";
        if(op == 3)
        {
            int ans = 0;
            pre(p , w , 0 , ans);
            fout << ans << "\n";
        }
    }
    return 0;
}