Cod sursa(job #2281229)

Utilizator trifangrobertRobert Trifan trifangrobert Data 11 noiembrie 2018 18:57:35
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <fstream>
#include <string>

using namespace std;

struct node
{
	int cnt;
	node* v[26];
	node()
	{
		cnt = 0;
		for (int i = 0;i < 26;++i)
			v[i] = NULL;
	}
	~node()
	{
		for (int i = 0;i < 26;++i)
			if (v[i] != NULL)
				delete v[i];
	}
};

struct trie
{
	node* root;
	trie()
	{
		root = new node();
	}
	~trie()
	{
		delete root;
	}
	void AddWord(const string &s) 
	{
		RecursiveAdd(s, root, 0);
	}
	void RecursiveAdd(const string &s, node* currNode, int i)
	{
		if (i == s.length())
		{
			++currNode->cnt;
			return;
		}
		if (currNode->v[s[i] - 'a'] == NULL)
			currNode->v[s[i] - 'a'] = new node();
		RecursiveAdd(s, currNode->v[s[i] - 'a'], i + 1);
	}
	void DeleteWord(const string &s)
	{
		RecursiveDelete(s, root, 0);
	}
	bool CanBeDeleted(node* x)
	{
		if (x->cnt != 0)
			return false;
		bool ok = false;
		for (int j = 0;j < 26;++j)
			ok |= (x->v[j] != NULL);
		return !ok;
	}
	bool RecursiveDelete(const string &s, node* currNode, int i)
	{
		if (i == s.length())
		{
			--currNode->cnt;
			return CanBeDeleted(currNode);
		}
		if (RecursiveDelete(s, currNode->v[s[i] - 'a'], i + 1))
		{
			delete currNode->v[s[i] - 'a'];
			currNode->v[s[i] - 'a'] = NULL;
			return CanBeDeleted(currNode);
		}
		return false;
	}
	int WordCount(const string &s)
	{
		return RecursiveCount(s, root, 0);
	}
	int RecursiveCount(const string &s, node* currNode, int i)
	{
		if (i == s.length())
			return currNode->cnt;
		if (currNode->v[s[i] - 'a'] == NULL)
			return 0;
		return RecursiveCount(s, currNode->v[s[i] - 'a'], i + 1);
	}
	int LongestPrefix(const string &s)
	{
		return RecursivePrefix(s, root, 0);
	}
	int RecursivePrefix(const string &s, node* currNode, int i)
	{
		if (i == s.length())
			return s.length();
		if (currNode->v[s[i] - 'a'] == NULL)
			return i;
		return RecursivePrefix(s, currNode->v[s[i] - 'a'], i + 1);
	}
};

int main()
{
	ifstream fin("trie.in");
	ofstream fout("trie.out");
	int tip;
	string s;
	trie T;
	while (fin >> tip)
	{
		fin >> s;
		if (tip == 0)
			T.AddWord(s);
		else if (tip == 1)
			T.DeleteWord(s);
		else if (tip == 2)
			fout << T.WordCount(s) << "\n";
		else
			fout << T.LongestPrefix(s) << "\n";
	}
	fin.close();
	fout.close();
	return 0;
}