Cod sursa(job #585508)

Utilizator mihaipopa12Popa Mihai mihaipopa12 Data 29 aprilie 2011 21:31:59
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include<stdio.h>
#include<string>

#define maxL 30
#define c (*p - 'a' + 1)

FILE*f=fopen("trie.in","r");
FILE*g=fopen("trie.out","w");

int app,L;
char sir[maxL];

struct Trie{
	
	int nr,nrfii; Trie *son[27];
	
	Trie(){
		
		nr = nrfii = 0;
		
		memset(son,0,sizeof(son));
	}
	
	
};

Trie *r = new Trie;

void insert( Trie *nod , char *p ){
	
	if ( *p == '\n' ){
		++nod -> nr;
		return ;
	}
	
	if ( nod -> son[c] == NULL ){
		nod -> son[c] = new Trie;
		++nod -> nrfii;
	}
	
	insert( nod -> son[c] , p + 1 );
}

bool erase ( Trie *nod , char *p ){
	
	if ( *p == '\n' ){
		--nod -> nr;
	}
	else{
		if ( nod -> son[c] ){
			if ( erase ( nod -> son[c] , p + 1 ) ){
				nod -> son[c] = NULL;
				--nod -> nrfii;
			}
		}
	}
	
	if ( !nod -> nrfii && !nod -> nr && nod != r ){
		delete nod;
		return 1;
	}
	return 0;
}

void appear ( Trie *nod , char *p ){
	
	if ( *p == '\n' ){
		app = nod -> nr;
		return ;
	}
	
	if ( nod -> son[c] ){
		appear( nod -> son[c] , p + 1 );
	}
	
}

void sc ( Trie *nod , char *p ){
	
	++L;
	
	if ( *p >= 'a' && *p <= 'z' && nod -> son[c] ){
		sc( nod -> son[c] , p + 1 );
	}
	
}

int main () {
	
	while ( fgets(sir+1,25,f) ){
		
		switch (sir[1]){
			
			case '0' :{
				
				insert(r,sir+3); break;
				
			}
			case '1' :{
				
				erase(r,sir+3); break;
				
			}
			case '2' :{
				
				app = 0; appear(r,sir+3);
				
				fprintf(g,"%d\n",app );
				
				break;
			}
			case '3' :{
				
				L = -1; sc(r,sir+3); 
				
				fprintf(g,"%d\n",L);
				
				break;
			}
			
		}
	}
	
	
	fclose(f);
	fclose(g);
	
	return 0;
}