Cod sursa(job #1580509)

Utilizator japjappedulapPotra Vlad japjappedulap Data 25 ianuarie 2016 21:39:48
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.35 kb
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;

ifstream cin ("trie.in");
ofstream cout ("trie.out");

struct Node{
    Node* next[26];
    int nrap, nrson;
    Node () { nrap = nrson = 0; memset(next, 0, sizeof(next)); }
};

Node *Root;
char C[22];

void Insert(Node* x, char* w);
bool Erase(Node* x, char* w);
int Count(Node* x, char* w);
int Prefix(Node* x, char* w, int Depth);

stack <char> S, ax, ax2;
void DEBUG(Node* x)
{
    ax = S;
    while (!ax.empty())
    { ax2.push(ax.top()); ax.pop();}
    while (!ax2.empty())
    { cout << ax2.top();ax2.pop(); }
    cout << ' ' << x->nrap << ' ' << x->nrson << '\n';
    for (int i = 0; i < 26; ++i)
        if (x->next[i] != 0)
        {
            S.push(i+'a');
            DEBUG(x->next[i]);
            S.pop();
        }
}

int main()
{
    int type;
    Root = new Node();

    while (cin >> type)
    {
        cin >> C;
        if (type == 0)
            Insert(Root, C);

        if (type == 1)
            Erase(Root, C);

        if (type == 2)
            cout << Count(Root, C) << '\n';

        if (type == 3)
            cout << Prefix(Root, C, 0) << '\n';
    }

    cin.close();
    cout.close();
}

void Insert(Node* x, char* w)
{
    if (*w == '\0'){
        x->nrap++;
        return;
    }
    if (x->next[*w-'a'] != 0)
        Insert(x->next[*w-'a'], w+1);
    else
        if (x->next[*w-'a'] == 0)
        {
            x->next[*w-'a'] = new Node();
            x->nrson++;
            Insert(x->next[*w-'a'], w+1);
        }
};

bool Erase(Node* x, char* w)
{
    if (*w == 0)
        x->nrap--;
    else
        if (Erase(x->next[*w - 'a'], w+1) == 1)
        {
            x->nrson--;
            x->next[*w - 'a'] = 0;
        }

    if (x != Root && x->nrson == 0 && x->nrap == 0)
    {
        delete x;
        return 1;
    }
    return 0;

};

int Count(Node* x, char* w)
{
    if (*w == '\0')
        return x->nrap;
    else
    {
        if (x->next[*w-'a'] == 0)
            return 0;
        else
            return Count(x->next[*w-'a'], w+1);
    }
};

int Prefix(Node* x, char* w, int Depth)
{
    if (*w == '\0')
        return Depth;
    if (x->next[*w-'a'] == 0)
        return Depth;
    else
        return Prefix(x->next[*w-'a'], w+1, Depth+1);
};