Cod sursa(job #1163121)

Utilizator irimiecIrimie Catalin irimiec Data 1 aprilie 2014 10:27:37
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <cstring>
#define CH (p[i] - 'a')

using namespace std;

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

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

Trie *T = new Trie;

void ins( Trie *nod, char p[] )
{
	int i = 0;
	
	while( p[ i ] != '\0' )
	{
		if( nod->fiu[ CH ] == 0 )
			nod->fiu[ CH ] = new Trie;
			
		nod = nod->fiu[ CH ];
		++nod->nrfii;
		++i;
	}
	
	++nod->cnt;
	return;
}

int del( Trie *nod, char p[] )
{
	int i = 0;
	while( p[ i ] != '\0' )
	{
		nod = nod->fiu[ CH ];
		--nod->nrfii;
		++i;
	}
	
	--nod->cnt;
	
	return 0;
}

int cat( Trie *nod, char *p )
{
	int i = 0;
	
	while( p[ i ] != '\0' )
	{
		if( !nod->fiu[ CH ] )
			return 0;
			
		nod = nod->fiu[ CH ];
		++i;
	}
	
	return nod->cnt;
}

int pre( Trie *nod, char p[] )
{
	int i = 0;
	
	while( p[ i ] != '\0' )
	{
		if( !nod->fiu[ CH ] )
			return i;
		
		nod = nod->fiu[ CH ];
		if( !nod->nrfii	 )
			return i;
		++i;
	}
	
	return i;
}

int main()
{
	int type = 0;
	char line[ 22 ];
	
	while( f >> type )
	{
		f >> line;
		switch( type )
		{
			case 0: ins( T, line ); break;
			case 1: del( T, line ); break;
			case 2: g << cat( T, line ) << "\n"; break;
			case 3: g << pre( T, line ) << "\n"; break;
		}
	}
	
	return 0;
}