Cod sursa(job #532470)

Utilizator laserbeamBalan Catalin laserbeam Data 11 februarie 2011 18:37:21
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.5 kb
#include <fstream>
#include <cstring>
#include <iostream>
using namespace std;

struct Nod
{
    Nod *next[26];
    int count;
    Nod *parent;
    int difNext;

    Nod(Nod *p)
    {
        count = 0;
        difNext = 0;
        for (int i = 0; i < 26; ++i)
            next[i] = NULL;
        parent = p;
    };
};

bool addWord( char *word, Nod *trie )
{
    int n = strlen(word);
    Nod *cnod = trie;
    for (int i = 0; i < n; ++i)
    {
        int ord = word[i] - 'a';
        if ( !cnod->next[ord] )
        {
            cnod->next[ord] = new Nod(cnod);
            cnod->difNext++;
        }
        cnod = cnod->next[ord];
    }
    cnod->count++;
    return true;
}

bool removeWord( char *word, Nod *trie )
{
    int n = strlen(word);
    Nod *cnod = trie;
    for (int i = 0; i < n; ++i)
    {
        int ord = word[i] - 'a';
        cnod = cnod->next[ord];
    }
    cnod->count--;
    int i = n-1;
    while ( cnod != trie && cnod->count == 0 && cnod->difNext == 0 )
    {
        Nod *aux = cnod;
        cnod = cnod->parent;
        delete aux;
        int ord = word[i] - 'a';
        i--;
        cnod->next[ord] = NULL;
        cnod->difNext--;
    }
    return true;
}

int countWords(char *word, Nod *trie)
{
    int n = strlen(word);
    Nod *cnod = trie;
    for (int i = 0; i < n; ++i)
    {
        int ord = word[i] - 'a';
        if (!cnod->next[ord]) return 0;
        cnod = cnod->next[ord];
    }
    return cnod->count;
}

int getPrefix(char *word, Nod *trie)
{
    int n = strlen(word);
    int len = 0;
    Nod *cnod = trie;
    for (int i = 0; i < n; ++i)
    {
        int ord = word[i] - 'a';
        if (!cnod->next[ord])
        {
            return len;
        }
        len++;
        cnod = cnod->next[ord];
    }
    return len;
}

int main()
{
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    int x;
    Nod trie(NULL);
    while (fin.good() && fin>>x)
    {
        char *word;
        fin>>word;
        if (!fin.good())
        {
            fin.close();
            fout.close();
            return 0;
        }
        switch (x)
        {
            case 0: addWord(word, &trie); break;
            case 1: removeWord(word, &trie); break;
            case 2: fout<<countWords(word, &trie)<<'\n'; break;
            case 3: fout<<getPrefix(word, &trie)<<'\n'; break;
            default: break;
        }
    }
    fin.close();
    fout.close();
    return 0;
}