Cod sursa(job #1338944)

Utilizator alexb97Alexandru Buhai alexb97 Data 10 februarie 2015 16:00:36
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

const int Sigma = 26;
ifstream is("trie.in");
ofstream os("trie.out");

struct Node{
	Node()
	{
		nr_cuv = nr_sons = 0;
		memset(sons, 0, sizeof(sons) );
	}
	
	int nr_sons;
	int nr_cuv;
	Node* sons[Sigma];
};

Node* R = new Node;
char word[Sigma];

void Read();

void Insert(Node *nod, char* s);
bool Del(Node *nod, char* s);
int Cuv(Node *nod, char* s);
int Litere(Node *nod, char* s, int k);

int main()
{
	Read();
	is.close();
	os.close();
	return 0;
}

void Read()
{
	while(is.getline(word, Sigma))
	{
		
		switch(word[0])
		{
			case '0' :	Insert (R, word + 2);						break;
			case '1' :	Del (R, word + 2);						break;
			case '2' :	os << Cuv (R, word + 2) << '\n';		break;
			case '3' :	os << Litere (R, word + 2, 0) << '\n';	break;
			
			default: cout << "Eroare!" << '\n';   break;
		}
		
	}
	
}
void Insert(Node *nod, char *s)
{
	if(*s == '\0')
	{
		nod->nr_cuv++;
		return;
	}
	if (nod->sons[*s - 'a'] == 0 )
	{
		nod->sons[*s - 'a'] = new Node;
		nod->nr_sons++;
	}
	
	Insert (nod->sons[*s - 'a'], s + 1 );
}

bool Del(Node *nod, char *s)
{
	if(*s == '\0')
	{
		nod->nr_cuv--;
	}
	else
		if(Del(nod->sons[*s - 'a'], s + 1)) //daca litera fiului e sters
		{
			nod->sons[*s - 'a'] = 0;
            nod->nr_sons--;
		}
	if(nod->nr_cuv == 0 && nod->nr_sons == 0 && nod != R)
	{
		delete nod;
		return true;
	}
	return false;
}

int Cuv(Node *nod, char *s)
{
	if(*s == '\0')
	{
		return nod->nr_cuv;
	}
	if(nod->sons[*s - 'a'])
	{
		return Cuv(nod->sons[*s-'a'], s+1);
	}
	return 0;
}

int Litere(Node *nod, char *s, int k)
{
	if ( *s == '\0' || nod->sons[*s - 'a'] == 0 )
        return k;
    return Litere( nod->sons[*s - 'a'], s + 1, k + 1 );
}