Cod sursa(job #2217614)

Utilizator alextodoranTodoran Alexandru Raul alextodoran Data 1 iulie 2018 10:20:44
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <bits/stdc++.h>

using namespace std;

struct Nod
{
    Nod* fii[26];
    int ap;
    int g;
    Nod()
    {
        for(int i = 0; i < 26; i++)
            fii[i] = NULL;
        ap = 0;
        g = 0;
    }
};

Nod* root = new Nod();

void trieInsert(Nod* root, const char* str)
{
    if (str[0] == '\0')
        root->ap++;
    else
    {
        if (root->fii[str[0] - 'a'] == NULL)
        {
            root->fii[str[0] - 'a'] = new Nod();
            root->g++;
        }
        trieInsert(root->fii[str[0] - 'a'], str + 1);
    }
}

int trieFind(Nod* root, const char* str)
{
    if (str[0] == '\0')
        return root->ap;
    else if (root->fii[str[0] - 'a'] == NULL)
        return 0;
    else
        return trieFind(root->fii[str[0] - 'a'], str + 1);
}

void trieErase(Nod* root, const char* str)
{
    if (str[0] == '\0')
        root->ap--;
    else
    {
        trieErase(root->fii[str[0] - 'a'], str + 1);
        if (root->fii[str[0] - 'a']->g == 0 && root->fii[str[0] - 'a']->ap == 0) {
            delete root->fii[str[0] - 'a'];
            root->fii[str[0] - 'a'] = NULL;
            root->g--;
        }
    }
}

int trieMaxPrefix(Nod* root, const char* str)
{
    if(str[0] == '\0' || root->fii[str[0] - 'a'] == NULL)
        return 0;
    else
        return trieMaxPrefix(root->fii[str[0] - 'a'], str + 1) + 1;
}

char lr[102];
int op;
string s;

int main()
{
    ifstream fin ("trie.in");
    ofstream fout ("trie.out");
    while(fin.getline(lr, 102))
    {
        int sz = strlen(lr);
        int op = 0;
        string s = "";
        op = lr[0] - '0';
        for(int i = 2; i < sz; i++)
            s += lr[i];
        if(op == 0)
            trieInsert(root, s.c_str());
        else if(op == 1)
            trieErase(root, s.c_str());
        else if(op == 2)
            fout << trieFind(root, s.c_str()) << "\n";
        else
            fout << trieMaxPrefix(root, s.c_str()) << "\n";
    }
    return 0;
}