Cod sursa(job #3166748)

Utilizator maiaauUngureanu Maia maiaau Data 9 noiembrie 2023 15:29:40
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>
using namespace std;
#define pb push_back

ifstream f("trie.in");
ofstream g("trie.out");

struct T{
	int cnt, cntf;
	T* F[27];
	T(){
		cnt = cntf = 0;
		for (int i = 0; i < 26; i++)
			F[i] = NULL;
	}
} *root;
char task, w[25];
void addw(), erasew();
int cntw(), prefw(); 

int main()
{
	root = new T;
	while (f >> task >> w){
		if (task == '0') addw();
		else if (task == '1') erasew();
		else if (task == '2') g << cntw() << '\n';
		else g << prefw() << '\n';
	}

	return 0;
}
void addw(){
	char *p = w; T *nod = root;
	while (*p) {
		int i = *p - 'a';
		if (nod->F[i] == NULL)
			nod->F[i] = new T;
		nod = nod->F[i];
		nod->cnt++;
		p++;
	}
	nod->cntf++;
}
void erasew(){
	char *p = w; T *nod = root;
	while (*p){
		int i = *p - 'a';
		nod = nod->F[i];
		nod->cnt--;
		p++;
	}
	nod->cntf--;
}
int cntw(){
	char *p = w; T *nod = root;
	while (*p){
		int i = *p - 'a';
		if (nod->F[i] == NULL || !nod->F[i]->cnt) return 0;
		nod = nod->F[i];
		p++;
	}
	return nod->cntf;
}
int prefw(){
	int l = 0;
	char *p = w; T *nod = root;
	while (*p){
		int i = *p - 'a';
		if (nod->F[i] == NULL || !nod->F[i]->cnt) return l;
		nod = nod->F[i];
		p++; l++;
	}
	return l;
}