Cod sursa(job #1293883)

Utilizator ptquake10ptquake10 ptquake10 Data 16 decembrie 2014 18:29:10
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <cstdio>
#include <fstream>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>
#include <stack>
#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <sstream>
#include <algorithm>
#include <exception>
using namespace std;

struct Trie{
	int num_words, num_prefixes;
	struct Trie* next[26];
	Trie() {
		num_words = num_prefixes = 0;
		for (int i = 0; i < 26; i++) {
			next[i] = NULL;
		}
}
void add_word(string s) {
	Trie* root = this;
	int next_char;
	for (int i = 0; i < s.length(); i++) {
		next_char = s[i] - 'a';
		if (root->next[next_char] == NULL) {
			root->next[next_char] = new Trie();
		}
			root = root->next[next_char];
			root->num_prefixes++;
	}
	root->num_words++;
}
void rem_word(string s) {
	Trie* root = this;
	int next_char;
	for (int i = 0; i < s.length(); i++) {
		next_char = s[i] - 'a';
		if (root->next[next_char] == NULL) {
			root->next[next_char] = new Trie();
		}
		root = root->next[next_char];
		root->num_prefixes--;
	}
	root->num_words--;
}
int num_of_occurances(string s) {
	Trie* root = this;
	int next_char;
	for (int i = 0; i < s.length(); i++) {
		next_char = s[i] - 'a';
		if (root->next[next_char] == NULL) {
			return 0;
		}
			root = root->next[next_char];
	}
	return root->num_words;
}
int longest_common_prefix(string s) {
	Trie* root = this;
	int next_char, longest_prefix = 0;
	for (int i = 0; i < s.length(); i++) {
		next_char = s[i] - 'a';
		if (root->next[next_char] == NULL) {
			return longest_prefix;
		}
			root = root->next[next_char];
			if (root->num_prefixes == 0) {
				return longest_prefix;
}
longest_prefix++;
	}
	return longest_prefix;
}
};

int n;
string s;

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

int main() {
	Trie *root = new Trie();
	while (f >> n >> s) {
		switch(n) {
			case 0: root->add_word(s); break;
			case 1: root->rem_word(s); break;
			case 2: g << root->num_of_occurances(s) << "\n"; break;			
			case 3: g << root->longest_common_prefix(s) << "\n"; break;
		}
	}

	return 0;
}