Cod sursa(job #2309014)

Utilizator mihai50000Mihai-Cristian Popescu mihai50000 Data 28 decembrie 2018 12:15:53
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
//#include <bits/stdc++.h>
#include <fstream>
#include <vector>
#include <bitset>
#include <unordered_map>
#include <algorithm>
#include <queue>
#include <math.h>
#include <iomanip>
#include <stack>
#include <string.h>
#include <set>
 
using namespace std;
 
ifstream in("trie.in");
ofstream out("trie.out");

struct Trie
{
	int apps;
	int word;
	
	Trie *next[27];
	Trie *father;
	
	Trie()
	{
		memset(next, 0, sizeof(next));
		apps = word = 0;
	}
	
	void add(string word, int pos = 0)
	{
		Trie *curr = this;
		
		if(pos == word.size())
			curr -> word++;
		else
		{
			if(curr -> next[word[pos] - 'a'] == NULL)
			{
				curr -> next[word[pos] - 'a'] = new Trie;
			}
			curr -> next[word[pos] - 'a'] -> add(word, pos + 1);
		}
		
		return ;
	}
	
	void erase(string word, int pos = 0)
	{
		Trie *curr = this;
		
		if(pos == word.size())
			curr -> word--;
		else
		{
			curr -> next[word[pos] - 'a'] -> erase(word, pos + 1);
			curr -> apps--;
			
			if(curr -> next[word[pos] - 'a'] -> apps == 0)
			{
				delete curr -> next[word[pos] - 'a'];
				curr -> next[word[pos] - 'a'] = 0;
			}
		}
		
		return ;
	}
	
	void find(string word, int pos = 0)
	{
		Trie *curr = this;
		
		if(pos != word.size())
		{
			if(curr -> next[word[pos] - 'a'] == NULL)
			{
				out << 0 << '\n';
				return ;
			}
			
			curr -> next[word[pos] - 'a'] -> find(word, pos + 1);
		}
		else
			out << curr -> word << '\n';
		
		return ;
	}
	
	void lcp(string word, int pos = 0)
	{
		Trie *curr = this;
		
		if(pos != word.size())
		{
			if(curr -> next[word[pos] - 'a'] == NULL)
				out << pos << '\n';
			else
				curr -> next[word[pos] - 'a'] -> lcp(word, pos + 1);
		}
		else
			out << word.size() << '\n';
		
		return ;
	}
};

Trie *trie = new Trie;

int main()
{
	int op;
	string word;
	
	while(in >> op >> word)
	{
		switch(op)
		{
			case(0):
				trie -> add(word);
				break;
			case(1):
				trie -> erase(word);
				break;
			case(2):
				trie -> find(word);
				break;
			case(3):
				trie -> lcp(word);
				break;
		}
	}
}