Cod sursa(job #1245901)

Utilizator tudi98Cozma Tudor tudi98 Data 20 octombrie 2014 10:44:50
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
using namespace std;

struct Trie{
  int edges;
  int words;
  Trie *edge[26];
  Trie(){
  	words = edges = 0;
  	for(int i = 0; i < 26; i++){
  	 	edge[i] = NULL;
  	}
  }
};

Trie *T = new Trie;

void addWord(Trie *node, char *s){
	if(*s == 0){
		node->words++;
		return; 
	}	
	if(node->edge[*s - 'a'] == NULL){
		node->edge[*s-'a'] = new Trie;
		node->edges++;	
	}
	addWord(node->edge[*s - 'a'], s+1);
}

bool delete_word(Trie *node, char *s){
	if(*s == 0){
		node->words--;
	}	
	else{
		if(delete_word(node->edge[*s - 'a'], s+1)){
			node->edges--;
			node->edge[*s - 'a'] = NULL;
		}
	}
	if(node->edges == 0 && node->words == 0 && node != T){
		delete node;
		return 1;
	}
	return 0;
}

int count_prefix(Trie *node, char *s,int pref){
	if(*s == 0) return pref;
	if(node->edge[*s - 'a'] != NULL){
		return count_prefix(node->edge[*s-'a'], s+1, pref+1);
	}
	return pref;
}
 
int count_words(Trie *node, char *s){
	if(*s == 0){
		return node->words; 
	}
	if(node->edge[*s - 'a'] == NULL)
		return 0;
	return count_words(node->edge[*s - 'a'], s+1);
}


int main(){

    ifstream fin("trie.in");
    ofstream fout("trie.out");

    int x;
    char a[26];
    while(fin >> x){
    	fin >> a;
    	if(x == 0){
    		addWord(T, a);	
    	}
    	else if(x == 1){
    	 	delete_word(T, a);
    	}
    	else if(x == 2){
    	    fout << count_words(T, a) << "\n";
    	}
    	else{
    	    fout << count_prefix(T, a, 0) << "\n";
    	}
    }
}