Cod sursa(job #2450772)

Utilizator r00t_Roman Remus r00t_ Data 24 august 2019 15:56:38
Problema Trie Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <queue>
#include <string>

using namespace std;

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

struct trie
{
	int freq, last;
	trie *neigh[27];
	trie()
	{
		freq = 0;
		last = 0;
		for (int i = 0; i < 27; i++) neigh[i] = NULL;
	}
};

trie *Root = new trie();

namespace trieOp
{
	void addWord(string &word,int ind, trie *&node)
	{
	
		if (node->neigh[word[ind] - 'a'] == NULL)
			node->neigh[word[ind] - 'a'] = new trie();
		if(ind<word.size())
			addWord(word, ind + 1, node->neigh[word[ind] - 'a']);
		node->freq++;
		if (ind == word.size()) node->last++;
	}
	void deleteWord(string &word, int ind, trie *& node)
	{
		if (node->neigh[word[ind] - 'a'] != NULL && ind<word.size())
			deleteWord(word, ind + 1, node->neigh[word[ind] - 'a']);
		node->freq--;
		if (ind == word.size()) node->last--;
		if (node->freq == 0) delete node, node = NULL;
	}

	int showApp(string &word, int ind, trie *& node)
	{
		if (node->neigh[word[ind] - 'a'] == NULL)
			return 0;
		else
		{
			if (ind == word.size())
				return node->last;
			else
				showApp(word, ind + 1, node->neigh[word[ind] - 'a']);
		}
	}

	int showPrefix(string &word, int ind, trie *&node)
	{
		if (ind == word.size())
			return ind;
		else
		{
			if (node->neigh[word[ind] - 'a'] != NULL)
				showPrefix(word, ind + 1, node->neigh[word[ind] - 'a']);
			else
				return ind;
		}
			
	}

}

int main()
{
	int t;
	string buff;
	while (fin >> t)
	{
		fin >> buff;
		if (t == 0) trieOp::addWord(buff, 0, Root);
		if (t == 1) trieOp::deleteWord(buff, 0, Root);
		if (t == 2)fout << trieOp::showApp(buff, 0, Root) << '\n';
		if (t == 3)fout << trieOp::showPrefix(buff, 0, Root) << '\n';

	}

}