Cod sursa(job #2984913)

Utilizator LXGALXGA a LXGA Data 25 februarie 2023 10:17:53
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
struct trie
{
	int cnt,l;
	trie* next[26];
	trie()
	{
		for(int i=0;i<26;i++)
			next[i]=nullptr;
		cnt=0;
		l=0;
	}
	void insert(const char* s)
	{
		l++;
		if(s[0]=='\0')
			cnt++;
		else
		{
			if(next[s[0]-'a']==nullptr)
				next[s[0]-'a']=new trie;
			next[s[0]-'a']->insert(s+1);
		}
	}
	int count(const char* s)
	{
		if(s[0]=='\0')
			return cnt;
		if(next[s[0]-'a']==nullptr)
			return 0;
		else
			return next[s[0]-'a']->count(s+1);
	}
	int lcp(const char* s)
	{
		if(s[0]=='\0')
			return 0;
		if(next[s[0]-'a']==nullptr)
			return 0;
		return 1+next[s[0]-'a']->lcp(s+1);
	}
	void erase(const char* s)
	{
		l--;
		if(s[0]=='\0')
			cnt--;
		else
		{
			next[s[0]-'a']->erase(s+1);
			if(next[s[0]-'a']->l==0)
			{
				delete next[s[0]-'a'];
				next[s[0]-'a']=nullptr;
			}
		}
	}
};
trie* r=new trie;
int c;
string s;
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	while(cin>>c>>s)
	{
		if(c==0)
			r->insert(s.c_str());
		else if(c==1)
			r->erase(s.c_str());
		else if(c==2)
			cout<<r->count(s.c_str())<<'\n';
		else
			cout<<r->lcp(s.c_str())<<'\n';
	}
	return 0;
}