Cod sursa(job #1758266)

Utilizator catalincraciunCraciun Catalin catalincraciun Data 16 septembrie 2016 21:30:42
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>

#define ch(x) (int)(x-'a')

using namespace std;

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

string w;

struct trie {
	int v;
	int childs;
	trie *son[26];

	trie() {
		v = 0;
		childs = 0;
		for (int i=0;i<26;i++)
			son[i] = NULL;
	}

	~trie() {
		for (int i=0;i<26;i++)
			delete son[i];
	}
};

trie *root;
trie *aux;

int go(trie *node, int index, int increment) {
	if (index < w.size()) {
		if (node->son[ch(w[index])] == NULL) {
			node->son[ch(w[index])] = new trie();
			node->childs++;
		}

		int toRet = go(node->son[ch(w[index])], index+1, increment);
		if (node->son[ch(w[index])]->v == 0 && node->son[ch(w[index])]->childs == 0) {
			node->childs--;
			delete node->son[ch(w[index])];
			node->son[ch(w[index])] = NULL;
		}

		return toRet;
	} else if (index == w.size()) {
		node->v += increment;
		return node->v;
	}

	return 0;
}

int ln(trie *node, int index) {
	if (index < w.size()) {
		if (node->son[ch(w[index])] == NULL)
			return 0;
		return 1+ln(node->son[ch(w[index])], index+1);
	} else
		return 0;
}

void read() {
	root = new trie();

	int tip;
	while (f>>tip) {
		f>>w;
		if (tip == 0) {
//			cout<<"Add "<<w<<endl;
			go(root, 0,1);
		} else if (tip == 1) {
//			cout<<"Delete "<<w<<endl;
			go(root, 0,-1);
		} else if (tip == 2) {
//			cout<<"Print occurances "<<w<<endl;
			g<<go(root, 0, 0)<<'\n';
		} else if (tip == 3) {
//			cout<<"Print longest prefix "<<w<<endl;
			g<<ln(root, 0)<<'\n';
		}
	}
}

int main() {

	read();

	f.close();
	g.close();

	return 0;
}