Cod sursa(job #2199664)

Utilizator emiemiEmi Necula emiemi Data 28 aprilie 2018 17:31:18
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 2.12 kb
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;

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

struct trie {
	char lit;
	int nr;
	int nrp;
	vector<trie *> next;
};

trie t;
trie *newt, *act;
int i, j, nsize, len;

void add(char *s) {
	len = strlen(s);
	
	act = &t;
	for (i = 0; i < len; ++i) {
		nsize = act->next.size();
		for (j = 0; j < nsize; ++j)
			if (act->next[j]->lit == s[i])
				break;
		
		if (j == nsize) {
			newt = (trie *)calloc(1, sizeof(trie));
			newt->lit = s[i];
			act->next.push_back(newt);
		}
		else {
			newt = act->next[j];
		}

		++act->nrp;
		act = newt;
	}

	++act->nr;
	++act->nrp;
}

void deleteWord(char *s) {
	len = strlen(s);

	act = &t;
	for (i = 0; i < len; ++i) {
		nsize = act->next.size();
		for (j = 0; j < nsize; ++j)
			if (act->next[j]->lit == s[i])
				break;

		--act->nrp;
		act = act->next[j];
	}

	--act->nr;
	--act->nrp;
}

void printNum(char *s) {
	len = strlen(s);

	act = &t;
	for (i = 0; i < len; ++i) {
		nsize = act->next.size();
		for (j = 0; j < nsize; ++j)
			if (act->next[j]->lit == s[i])
				break;

		if (j == nsize) {
			break;
		}

		act = act->next[j];
	}
	
	if (i < len)
		g << "0\n";
	else
		g << act->nr << "\n";
}

void pref(char *s) {
	int pr = 0;
	len = strlen(s);

	act = &t;

	nsize = act->next.size();
	for (j = 0; j < nsize; ++j)
		if (act->next[j]->lit == s[0])
			break;

	if (j == nsize || act->nrp == 0) {
		g << "0\n";
		return;
	}

	act = act->next[j];
	for (i = 1; i < len; ++i) {
		if (act->nrp != 0)
			++pr;
		else
			break;

		nsize = act->next.size();
		for (j = 0; j < nsize; ++j)
			if (act->next[j]->lit == s[i])
				break;

		if (j == nsize)
			break;

		act = act->next[j];
	}

	g << pr << '\n';
}

int main() {
	char *s = (char *)calloc(25, sizeof(char));

	while (!f.eof()) {
		f.getline(s, 25);
		switch (s[0]) {
		case '0':
			add(s + 2);
			break;
		case '1':
			deleteWord(s + 2);
			break;
		case '2':
			printNum(s + 2);
			break;
		case '3':
			pref(s + 2);
			break;
		}
	}

	return 0;
}