Cod sursa(job #3320764)

Utilizator Botnaru_VictorBotnaru Victor Botnaru_Victor Data 7 noiembrie 2025 11:21:03
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#include <bits/stdc++.h>
using namespace std;
//#define TESTS

#define x first
#define y second
#define pii pair<int,int>
#define veci vector<int>
#define vecp vector<pii>
#define all(x) x.begin(), x.end()
#define pb(x,y) x.push_back(y)

const int maxn = 11;
const int maxa = 27;
struct TrieNod{
	int ap=0;
	int fin=0;
	TrieNod *next[maxa] = {NULL};

	TrieNod *get(int id)
	{
		if(next[id]==NULL) next[id] = new TrieNod;
		return next[id];
	}

	~TrieNod()
	{
		for(int i=0;i<maxa;i++)
		{
			if(next[i]!=NULL) delete next[i];
		}
	}
};

struct Trie{
	TrieNod *root;
	Trie()
	{
		root = new TrieNod;
	}

	void insert(char s[])
	{
		TrieNod *current = root;
		int i=0;
		while(s[i]!='\0')
		{
			current->ap++;
			current = current->get(s[i++]-'a');
		}

		current->ap++;
		current->fin++;
	}

	int count(char s[])
	{
		TrieNod *current = root;
		int i=0;
		while(s[i]!='\0'&&current!=NULL) current = current->next[s[i++]-'a'];
		if(s[i]!='\0'||current==NULL) return 0;
		return (current->fin);
	}

	void remove(char s[])
	{
		TrieNod *current = root;
		int i=0;
		while(s[i]!='\0'&&current!=NULL) current->ap--, current = current->next[s[i++]-'a'];
		current->fin--;
		current->ap--;
	}

	int longest_prefix(char s[])
	{
		TrieNod *current = root;
		int i=0;
		while(s[i]!='\0'&&current!=NULL&&(current->ap)>0)
		{
			current = current->next[s[i]-'a'];
			if((current==NULL)||(current->ap)==0) return i;
			//cerr<<"HERE "<<s[i]<<' '<<(current!=NULL)<<' '<<((current!=NULL)?(current->ap):0)<<'\n';
			i++;
			if(s[i]=='\0') return i;
		}
		return -1;
		
	}

	~Trie()
	{
		delete root;
	}
};

void solve()
{
	Trie tri;
	int c; char buf[25];

	while(cin>>c)
	{
		cin>>buf;
		switch(c)
		{
			case 0:
				tri.insert(buf);
				break;
			case 1:
				tri.remove(buf);
				break;
			case 2:
				cout<<tri.count(buf)<<'\n';
				break;
			case 3:
				cout<<tri.longest_prefix(buf)<<'\n';
				break;
			default:
				assert(0);
		}
		//cerr<<tri.count("lat")<<'\n';
	}
}

int32_t main()
{
	#ifndef LOCAL
		#define fname "trie"
		freopen(fname".in","r", stdin);
		freopen(fname".out","w",stdout);
	#endif

	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(0);

	int t=1;

	#ifdef TESTS
		cin>>t;
	#endif
	while(t--)
	{
		solve();
	}
	return 0;
}