Cod sursa(job #2702724)

Utilizator ssenseEsanu Mihai ssense Data 5 februarie 2021 16:41:05
Problema Trie Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 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 Vertex {
	int next[K];
	bool leaf = false;
	int num = 0;
	int connections = 0;
	Vertex() {
		fill(begin(next), end(next), -1);
	}
};

vector<Vertex> t(1);

void add_string(string const& s) {
	int v = 0;
	for (char ch : s) {
		int c = ch - 'a';
		if (t[v].next[c] == -1) {
			t[v].next[c] = t.size();
			t[v].connections+=1;
			t.emplace_back();
		}
		v = t[v].next[c];
	}
	t[v].num+=1;
	t[v].leaf = true;
}

void delete_app(string s)
{
	int v = 0;
	int last = 0;
	char l = 'a';
	for(char ch : s)
	{
		int c = ch-'a';
		if(t[v].connections > 1 || (t[v].leaf && t[v].next[c] != -1))
		{
			l = ch;
			last = v;
		}
		v = t[v].next[c];
	}
	if(t[v].num == 1)
	{
		t[last].connections-=1;
		t[last].next[l-'a']=-1;
	}
	t[v].num-=1;
}

void print_app(string s)
{
	int v = 0;
	for(char ch : s)
	{
		int c = ch-'a';
		if (t[v].next[c] == -1) {
			cout << 0 << endl;
			return;
		}
		v = t[v].next[c];
	}
	cout << t[v].num << endl;
}

void long_prefix(string s)
{
	int v = 0;
	int len = 0;
	for(char ch : s)
	{
		int c = ch-'a';
		if(t[v].next[c] == -1)
		{
			break;
		}
		len++;
		v = t[v].next[c];
	}
	cout << len << endl;
}

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)
		{
			add_string(s);
		}
		if(c == 1)
		{
			delete_app(s);
		}
		if(c == 2)
		{
			print_app(s);
		}
		if(c == 3)
		{
			long_prefix(s);
		}
	}
}