Cod sursa(job #2449617)

Utilizator r00t_Roman Remus r00t_ Data 20 august 2019 11:41:05
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <map>
#include <stdio.h>

using namespace std;

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

const int SIGMA = 26;

struct trie
{
	int freq;
	int leaf;
	trie *neigh[SIGMA];
	trie()
	{
		this->freq = 0;
		this->leaf = 0;
		memset(this->neigh, NULL, sizeof(this->neigh));
	}
};

trie *Root = new trie();

namespace trieOp
{
	void insert(trie *&node, string &buff, int ind)
	{
		node->freq++;
		if (ind == buff.size())
		{
			node->leaf++;
			return;
		}
		else
		{
			int togo = buff[ind] - 'a';
			if (node->neigh[togo] == nullptr)
				node->neigh[togo] = new trie();
			insert(node->neigh[togo], buff, ind + 1);
		}
	}

	void remove(trie *&node, string &buff, int ind)
	{
		node->freq--;
		if (ind == buff.size())
		{
			node->leaf--;
		}
		else
		{
			int togo = buff[ind] - 'a';
			remove(node->neigh[togo], buff, ind + 1);
		}
		if (node != Root && node->freq == 0)
			delete node, node = nullptr;
	}

	int get_freq(trie *&node, string &buff, int ind)
	{
		if (buff.size() == ind)
		{
			return node->leaf;
		}
		else
			if(node->neigh[buff[ind] - 'a'] != nullptr)
				get_freq(node->neigh[buff[ind]-'a'], buff, ind + 1);
		return 0;
	}

	int  get_longest_prefix(trie *&node, string &buff, int ind)
	{
		if (node->freq > 0 && ind < buff.size())
		{
			int togo = buff[ind] - 'a';
			if (node->neigh[togo] != nullptr)
			{
				return get_longest_prefix(node->neigh[togo], buff, ind + 1);
			}
		}
		return ind;
	}
}





int main()
{
	int t;
	string buff;
	while (fin >> t)
	{
		fin >> buff;
		switch (t)
		{
		case 0:
			trieOp::insert(Root, buff, 0);
			break;
		case 1:
			trieOp::remove(Root, buff, 0);
			break;
		case 2:
			fout << trieOp::get_freq(Root, buff, 0) << '\n';
			break;
		case 3:
			fout << trieOp::get_longest_prefix(Root, buff, 0) << '\n';
			break;
		}
	}


}