Cod sursa(job #2465826)

Utilizator Johnny07Savu Ioan-Daniel Johnny07 Data 30 septembrie 2019 21:36:18
Problema Trie Scor 25
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");


struct trie
{
	int nr_cuv, nr_stramosi;
	trie* father;
	trie* fiu[30];
	trie()
	{
		for (int i=1;i<=29;i++)
		{ 
			fiu[i] = NULL;
		}
		father = NULL;
		nr_cuv = 0;
		nr_stramosi = 0;
	}
};

trie* root = new trie;

void add(string& s)
{
	trie* temp = root;
	int num, i, n = s.size();

	for (i = 0; i < n; i++)
	{
		num = s[i] - 96;
		if (temp->fiu[num] == NULL) temp->fiu[num] = new trie;
		temp->nr_stramosi++;
		(temp->fiu[num])->father = temp;
		temp = temp->fiu[num];
	}
	temp->nr_cuv++;
	
}

void delet(string& s)
{

	trie* temp = root;
	int num, i, n = s.size();
	for (i = 0; i < n; i++)
	{
		num = s[i] - 96;
		temp = temp->fiu[num];
	}
	temp->nr_cuv--;
	i--;
	
	while (temp->nr_cuv == 0 && temp->nr_stramosi <= 1  && i>=0)
	{
		num = s[i] - 96;
		temp = temp->father;
		delete temp->fiu[num];
		temp->fiu[num] = NULL;
		i--;
	}

}


void find(string& s)
{
	trie* temp = root;
	int num, i, n = s.size();
	for (i = 0; i < n; i++)
	{
		num = s[i] - 96;
		if (temp->fiu[num] == NULL)
		{
			g << 0 << endl;
			return;
		}
		else temp = temp->fiu[num];
	}
	g << temp->nr_cuv << endl;
}

void prefix(string& s)
{
	trie* temp = root;
	int num, i, n = s.size();
	int sol = 0;
	for (i = 0; i < n; i++)
	{
		num = s[i] - 96;
		if (temp->fiu[num] == NULL)
		{
			g << sol << endl;
			return;
		}
		sol++;
		temp = temp->fiu[num];
	}
	g << sol << endl;

}


int main()
{
	string s;
	int x;
	while (!f.eof())
	{
		f >> x >> s;
		if (x == 0) add(s);
		if (x == 1) delet(s);
		if (x == 2) find(s);
		if (x == 3) prefix(s);
	}


	return 0;
}