Cod sursa(job #1910918)

Utilizator tonisnakesBoar Antonio tonisnakes Data 7 martie 2017 18:48:04
Problema Trie Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <iostream>
#include <fstream>
#include <cstring>
#define SMAX 25
#define SIGMAR 30
using namespace std;

ifstream fin ("trie.in");
ofstream fout ("trie.out");

char s[SMAX];
struct Nod {
	int cnt, nrfii;
	Nod *sons[SIGMAR];
	Nod () {
		memset(sons, 0, sizeof(sons));
		/*for (int i = 0; i < SIGMAR; ++i) {
			sons[i] = NULL;
		}*/
		cnt = 0;
		nrfii = 0;
	}
};
Nod *root = new Nod();

void insert (Nod *nod, char *s) {
	if (!*s) {
		nod->cnt += 1;
	}
	else {
		int son = *s - 'a';
		if (!nod->sons[son]) {
			nod->sons[son] = new Nod();
			nod->nrfii += 1;
		}
		insert(nod->sons[son], s+1);
	}
}

int del (Nod *nod, char *s) {
	if (!*s) {
		nod->cnt -= 1;
		if (nod->cnt == 0 && nod->nrfii == 0 && nod != root) {
			delete nod;
			//nod = NULL;
			return 1;
		}
		return 0;
	}
	else {
		int son = *s - 'a';
		if (!nod->sons[son]) {
			return 0;
		}
		if (del(nod->sons[son], s+1)) {
			nod->nrfii -= 1;
			nod->sons[son] = 0;
			if (nod->cnt == 0 && nod->nrfii == 0 && nod != root) {
				delete nod;
				//nod = NULL;
				return 1;
			}
		}
		return 0;
	}
	return 0;
}

int dfs (Nod *nod, char *s) {
	if (!*s) {
		//cout << nod->cnt;
		int ret = nod->cnt;
		//cout << ret;
		return ret;
	}
	else {
		int son = *s - 'a';
		if (!nod->sons[son]) {
			return 0;
		}
		dfs(nod->sons[son], s+1);
	}
	//return 0;
}

void afis (Nod *nod, int level) {
	for (int i = 0; i < 26; ++i) {
		if (!nod->sons[i]) {
			continue;
		}
		for (int j = 1; j <= level; ++j) {
			cout << " ";
		}
		char c = i + 'a';
		cout << c << " " << nod->sons[i]->cnt << endl;
		afis(nod->sons[i], level+1);
	}
}

int prefix (Nod *nod, char *s) {
	if (!*s) {
		return 0;
	}
	int son = *s - 'a';
	if (nod->sons[son]) {
		return 1 + prefix(nod->sons[son], s+1);
	}
	return 0;
}

int main ()
{
	while (fin.getline(s, SMAX)) {
		if (s[0] == '0') {
			insert(root, s+2);
		}
		else
		if (s[0] == '1') {
			del(root, s+2);
		}
		else
		if (s[0] == '2') {
			fout << dfs(root, s+2) << endl;
		}
		else {
			fout << prefix(root, s+2) << endl;
		}
		/*afis(root,0);
		cout << endl;*/
	}
	//afis(nod,0);
	
	fin.close();
	fout.close();
	return 0;
}