Cod sursa(job #1415235)

Utilizator andrei_toaderToader Andrei Sorin andrei_toader Data 3 aprilie 2015 23:45:32
Problema Trie Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
#include <fstream>
#include <cstring>

typedef struct _trie {
    int numberOfWords;
	int numberOfPasses;
    _trie* nodes[26];
    _trie() {
        numberOfWords = 0;
		numberOfPasses = 0;
        for (int i = 0; i<26; i++)
        {
            nodes[i] = NULL;
        }
    }
}trie;

using namespace std;

int numberOfWordsGlobal;

void add(trie* root, char* s) {
    if (*s == 0) {
        root->numberOfWords += 1;
        return;
    }
    if (root->nodes[s[0]-'a'] == NULL)
    {
        root->nodes[s[0] - 'a'] = new trie;
    }
	root->nodes[s[0] - 'a']->numberOfPasses += 1;
    add(root->nodes[s[0] - 'a'],s+1);
}

void sterge(trie* root, char* s)
{
	if (*s == NULL)
	{
		root->numberOfWords -= 1;
	}
	else
	{
		root->nodes[s[0] - 'a']->numberOfPasses -=1;
		sterge(root->nodes[s[0] - 'a'],s+1);
	}
}

int searchAparitie(trie* root, char*s)
{
	if (*s == NULL)
	{
		return root->numberOfWords;
	}
	else if (root->nodes[s[0] -'a'] != NULL)
	{
		return searchAparitie(root->nodes[s[0] - 'a'],s+1);
	}
	else 
	{
		return 0;
	}
}

int getMaxNumber(trie* root,char* s)
{
	int rez = 0;
	trie t = *root;
	for (int i = 0; i<strlen(s); i++)
	{
		if (t.nodes[s[i] - 'a'] != NULL && t.nodes[s[i]-'a']->numberOfPasses != 0)
		{
			rez += 1;
			t = *(t.nodes[s[i]-'a']);
		}
		else
		{
			break;
		}
	}
	return rez;
}

int main() {
    int type;
    char s[25];
    trie* root;
    ifstream f("trie.in");
    ofstream g("trie.out");
    root = new trie;
	numberOfWordsGlobal = 0;
    while (! f.eof())
    {
        f>>type>>s;
        if (type == 0)
        {
			++numberOfWordsGlobal;
            add(root,s);
        }
        else if (type == 1)
        {
			--numberOfWordsGlobal;
			sterge(root,s);
        }
        else if (type == 2)
        {
			g<<searchAparitie(root,s)<<"\n";
        }
        else
        {
			g<<getMaxNumber(root,s)<<"\n";
        }
    }

	return 0;
}