Cod sursa(job #2703061)

Utilizator ssenseEsanu Mihai ssense Data 6 februarie 2021 22:13:49
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 kb
#include <bits/stdc++.h>
#define startt ios_base::sync_with_stdio(false);cin.tie(0);
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
typedef unsigned long long ull;
typedef long long  ll;
using namespace std;
#define FOR(n) for(int i=0;i<n;i++)
#define vt vector
#define vint vector<int>
#define all(v) v.begin(), v.end()
#define MOD 1000000007
#define MOD2 998244353
#define MX 1000000000
#define nax 100005
#define MXL 1000000000000000000
#define PI 3.14159265
#define pb push_back
#define pf push_front
#define sc second
#define fr first
#define int ll
#define endl '\n'
#define ld long double

vector<int> read(int n) {vector<int> a; for (int i = 0; i < n; i++) { int x; cin >> x; a.pb(x);} return a;}

const int K = 26;

struct Trie
{
	int cnt, cons;
	Trie *fii[K];
	Trie()
	{
		cnt = 0;
		cons = 0;
		memset(fii, 0, sizeof(fii));
	}
};

Trie *T = new Trie;

void insert(Trie *nod, string s, int now)
{
	int ch = s[now]-'a';
	if(s[now] == '\0')
	{
		nod->cnt++;
		return;
	}
	if(nod->fii[ch] == 0)
	{
		nod->fii[ch] = new Trie;
		nod->cons++;
	}
	insert(nod->fii[ch], s, now+1);
}

int del(Trie *nod, string s, int now)
{
	if(s[now] == '\0')
	{
		nod->cnt--;
	}
	else if(del(nod->fii[s[now]-'a'], s, now+1) == 1)
	{
		nod->fii[s[now]-'a'] = 0;
		nod->cons--;
	}
	if(nod->cnt == 0 && nod->cons == 0 && nod!= T)
	{
		delete nod;
		return 1;
	}
	return 0;
}

int que(Trie *nod, string s, int now)
{
	if(s[now] == '\0')
	{
		return nod->cnt;
	}
	if(nod->fii[s[now]-'a'] != 0)
	{
		return que(nod->fii[s[now]-'a'], s, now+1);
	}
	return 0;
}

int longpref(Trie *nod, string s, int now, int res)
{
	if(s[now] == '\0' || nod->fii[s[now]-'a'] == 0)
	{
		return res;
	}
	else
	{
		return longpref(nod->fii[s[now]-'a'], s, now+1, res+1);
	}
}

int32_t main(){
	startt;
	freopen("trie.in", "r", stdin);
	freopen("trie.out", "w", stdout);
	int c;
	while(cin >> c)
	{
		string s;
		cin >> s;
		if(c == 0)
		{
			insert(T, s, 0);
		}
		if(c == 1)
		{
			del(T, s, 0);
		}
		if(c == 2)
		{
			cout << que(T, s, 0) << endl;
		}
		if(c == 3)
		{
			cout << longpref(T, s, 0, 0) << endl;
		}
	}
}