Cod sursa(job #2651244)

Utilizator PaulTPaul Tirlisan PaulT Data 21 septembrie 2020 20:08:26
Problema Trie Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
// Trie - infoarena
#include <fstream>
#include <cstring>
using namespace std;

class Dictionary {
public:
	Dictionary() : root {new Trie()}
	{}
	
	void insert(const char* word)
	{
		insert(word, root);
	}
	
	void remove(const char* word)
	{
		remove(word, root);
	}
	
	int query(const char* word)
	{
		return query(word, root);
	}
	
	int prefix(const char* word)
	{
		return prefix(word, root);
	}
	
private:
	struct Trie {
		Trie(const char& ch = 'a') : cnt {0}, sonsCnt {0}
		{}
		
		int cnt;
		int sonsCnt;
		Trie* sons[26];
	};
	
	void insert(const char* word, Trie* trie)
	{
		if (strlen(word) == 0)
		{
			trie->cnt++;
			return;
		}
		
		if (trie->sons[word[0] - 'a'] == nullptr)
		{
			trie->sons[word[0] - 'a'] = new Trie();
			trie->sonsCnt++;
		}
		insert(word + 1, trie->sons[word[0] - 'a']);
	}

	bool remove(const char* word, Trie* trie)	// true if trie has been deleted
	{
		if (strlen(word) == 0)
			trie->cnt--;
		else
		{
			if (remove(word + 1, trie->sons[word[0] - 'a']))
			{
				trie->sons[word[0] - 'a'] = nullptr;
				trie->sonsCnt--;
			}
		}
		
		if (trie->cnt == 0 && trie->sonsCnt == 0 && trie != root)
		{
			delete trie;
			return true;
		}
		return false;
	}

	int query(const char* word, Trie* trie)
	{
		if (trie == nullptr)
			return 0;
		if (strlen(word) == 0)
			return trie->cnt;
		
		return query(word + 1, trie->sons[word[0] - 'a']);
	}

	int prefix(const char* word, Trie* trie)
	{
		if (trie == nullptr || strlen(word) == 0 || 
			trie->sons[word[0] - 'a'] == nullptr)
			return 0;

		return 1 + prefix(word + 1, trie->sons[word[0] - 'a']);
	}

	Trie* root;
};

ifstream fin("trie.in");
ofstream fout("trie.out");
Dictionary dict;

int main()
{
	int type;
	char word[21];
	
	while (fin >> type >> word)
		switch (type)
		{
			case 0:
				dict.insert(word);
				break;
			case 1:
				dict.remove(word);
				break;
			case 2:
				fout << dict.query(word) << '\n';
				break;
			case 3:
				fout << dict.prefix(word) << '\n';
				break;
		}
	
	fin.close();
	fout.close();
}