Cod sursa(job #2569233)

Utilizator mihai50000Mihai-Cristian Popescu mihai50000 Data 4 martie 2020 11:34:44
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;

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

const int sigma = 26;

struct Trie
{
	Trie* next[sigma];
	int cuv;
	int pre;
	
	Trie()
	{
		for(int i = 0; i < sigma; ++i)
			next[i] = nullptr;
		
		cuv = pre = 0;
	}
	
	void insert(string s)
	{
		Trie* now = this;
		
		for(auto i : s)
		{
			if(now -> next[i - 'a'] == nullptr)
			{
				now -> next[i - 'a'] = new Trie;
			}
			
			now = now -> next[i - 'a'];
			++now -> pre;
		}
		
		++now -> cuv;
	}
	
	void pop(string s)
	{
		Trie* now = this;
		
		for(auto i : s)
		{
			now = now -> next[i - 'a'];
			--now -> pre;
		}
		
		--now -> cuv;
	}
	
	int query1(string s)
	{
		Trie* now = this;
		
		for(auto i : s)
		{
			if(now -> next[i - 'a'] == nullptr)
				return 0;
			
			now = now -> next[i - 'a'];
		}
		
		return now -> cuv;
	}
	
	int query2(string s)
	{
		Trie* now = this;
		
		int pos = 0;
		
		for(auto i : s)
		{
			if(now -> next[i - 'a'] == nullptr || now -> next[i - 'a'] -> pre == 0)
				return pos;
			
			now = now -> next[i - 'a'];
			++pos;
		}
		
		return int(s.size());
	}
};

Trie *root = new Trie;

main()
{
	int op;
	string s;
	
	while(fin >> op >> s)
	{
		if(op == 0)
		{
			root -> insert(s);
			continue;
		}
		
		if(op == 1)
		{
			root -> pop(s);
			continue;
		}
		
		if(op == 2)
		{
			fout << root -> query1(s) << '\n';
			continue;
		}
		
		if(op == 3)
		{
			fout << root -> query2(s) << '\n';
			continue;
		}
	}
}