Cod sursa(job #2653700)

Utilizator filicriFilip Crisan filicri Data 28 septembrie 2020 20:26:22
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>
#include <cstring>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");

char w[26];
int op;

struct node {
	int sons_counter, app_counter;
	node* son[26];
	node() {
		sons_counter = app_counter = 0;
		memset(son, 0, sizeof(son));
	}
};

node* root = new node();

void add(node* curr_node, char* word) {
	if(*word == NULL) {
		curr_node -> app_counter++;
		return;
	}
	int idx = *word - 'a';
	if(curr_node -> son[idx] == NULL) {
		curr_node -> son[idx] = new node();
		curr_node -> sons_counter++;
	}
	add(curr_node -> son[idx], word + 1);
}

int count_app(node* curr_node, char* word) {
	if(*word == NULL) 
		return curr_node -> app_counter;
	int idx = *word - 'a';
	if(curr_node -> son[idx] == NULL)
		return 0;
	count_app(curr_node -> son[idx], word + 1);
}

int delete_app(node* curr_node, char* word) {
	if(*word == NULL) {
		curr_node -> app_counter--;
		if(curr_node -> app_counter == 0 && curr_node -> sons_counter == 0 && curr_node != root) {
			delete curr_node;
			return 1;
		}
		return 0;
	}
	int idx = *word - 'a';
	if(delete_app(curr_node -> son[idx], word + 1)) {
		curr_node -> sons_counter--;
		curr_node -> son[idx] = 0;
		if(curr_node -> app_counter == 0 && curr_node -> sons_counter == 0 && curr_node != root) {
			delete curr_node;
			return 1;
		}
	}
	return 0;
}

int count_cp(node* curr_node, char* word) {
	int idx = *word - 'a';
	if (*word == NULL || curr_node -> son[idx] == NULL)
		return 0;
	return 1 + count_cp(curr_node -> son[idx], word + 1);
}

int main() {
	while(f>>op) {
		f>>w;
		if(op == 0)
			add(root, w);
		else if(op == 1)
			delete_app(root, w);
		else if(op == 2)
			g << count_app(root, w) << '\n';
		else
			g << count_cp(root, w) << '\n'; 
	}

	f.close();
	g.close();
	return 0;
}