Cod sursa(job #694804)

Utilizator gener.omerGener Omer gener.omer Data 28 februarie 2012 00:39:25
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <cstdio>
#include <iostream>

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));
	}
};

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->cnt--;
	}

	if(T->cnt == 0 && T->no_sons == 0)
		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);
	Trie * T = new Trie();
	while(scanf("%d %s", &code, w) != EOF){
		switch(code){
		case 0:
			add(T, w);
			break;
		case 1:
			//del(T, w);
			break;
		case 2:
			printf("%d\n", find_occurences(T, w));
			break;
		case 3:
			printf("%d\n", find_largest_prefix(T, w, 0));
			break;
		break;
		}
	}

	return 0;
}