Cod sursa(job #887412)

Utilizator veleanduAlex Velea veleandu Data 23 februarie 2013 19:09:45
Problema Trie Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <cstdio>
#include <fstream>

#include <string>
#include <vector>
using namespace std;

#define max_l 25
#define FORIT( it,v ) for( typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it )

string text;
int t;

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

struct trie{
	int val,under;
	int Next[ 26 ];
	trie(){
		for( int i=0; i<26; ++i ){
			Next[ i ] = -1;
		}
		val=0;
	}
} ;
vector<trie> T;

int add( int v ){
	int act=0;
	FORIT( it, text ){
		if( T[ act ].Next[ *it-'a' ] == -1 ){
			T.push_back( trie() );
			T[ act ].Next[ *it-'a' ] = T.size()-1;
		}
		act = T[ act ].Next[ *it-'a' ];
		T[ act ].under+=v;
	}
	T[ act ].val+=v;
	return T[ act ].val;
}

int prefix(){
	int act=0,rez=0,i=0;
	FORIT( it, text ){
		if( T[ act ].Next[ *it-'a' ] == -1 )
			return rez;
		act = T[ act ].Next[ *it-'a' ];
		++i;
		if( T[ act ].under )
			rez=i;
	}
	return rez;
}

void solve(){
	while( in>>t ){
		in>>text;
		switch( t ){
			case 0:
				add( 1 );
			break;
			case 1:
				add( -1 );
			break;
			case 2:
				out<<add( 0 )<<"\n";
			break;
			case 3:
				out<<prefix()<<"\n";
			break;
		}
	}
}

int main(){
	T.push_back( trie() );
	solve();
	return 0;
}