Cod sursa(job #697059)

Utilizator gener.omerGener Omer gener.omer Data 28 februarie 2012 21:53:45
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

#define MAX 25

char w[MAX];
int code;

struct Trie{
	int cnt, no_sons;
	Trie * son[26];
	Trie(){
		cnt = no_sons = 0;
		memset(son, 0, sizeof(son));
	}
};

Trie * root;

void add(Trie * T, char * w){
	if(*w == 0){ T->cnt++; return;}
	if(!T->son[*w - 'a']){
		T->son[*w - 'a'] = new Trie();
		T->no_sons++;
	}
	add(T->son[*w - 'a'], w + 1);
}

int del(Trie * T, char * w){
	if(*w == 0)
		T->cnt--;
	else if(del(T->son[*w - 'a'], w + 1)){
		T->son[*w - 'a'] = 0;
		T->no_sons--;
	}

	if(T->cnt == 0 && T->no_sons == 0 && T != root){ delete T; return 1;}

	return 0;
}

int find_occurences(Trie * T, char * w){
	if(*w == 0){ return T->cnt;}
	if(T->son[*w - 'a'])
		return find_occurences(T->son[*w - 'a'], w + 1);
	return 0;
}

int find_largest_prefix(Trie * T, char * w, int k){
	if(*w == 0 || T->son[*w - 'a'] == 0)
		return k;
	return find_largest_prefix(T->son[*w - 'a'], w + 1, k + 1);
}

int main(){
	freopen("trie.in", "r", stdin);
	freopen("trie.out", "w", stdout);
	root = new Trie();
	while(scanf("%d %s", &code, w) != EOF){
		switch(code){
		case 0:
			add(root, w);
			break;
		case 1:
			del(root, w);
			break;
		case 2:
			printf("%d\n", find_occurences(root, w));
			break;
		case 3:
			printf("%d\n", find_largest_prefix(root, w, 0));
			break;
		break;
		}
	}

	return 0;
}