Cod sursa(job #754425)

Utilizator alexeiIacob Radu alexei Data 2 iunie 2012 00:43:21
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include<fstream>
using namespace std;

#define NMAX 20000010

int sz = 0, p_sz = 0;
char P[NMAX],S[NMAX];
int PI[NMAX],ans[1024];

void compute_pie()
{
	PI[0] = 0;
	
	int i , k = 0;
	for( i = 1; i < p_sz; ++i )
	{
		while( k && P[k] != P[i] )
			k = PI[k];

		if( P[k] == P[i] )
			++k;

		PI[i] = k;
	}
}

int main()
{
	fstream f ("strmatch.in",  fstream::in );
	fstream g ("strmatch.out", fstream::out );
	
	//freopen("kmp.in","r",stdin);
	//freopen("kmp.out","w",stdout);

	f.getline(P,NMAX);
	f.getline(S,NMAX);

	//fgets(P,NMAX,stdin);
	//fgets(S,NMAX,stdin);

	while( P[p_sz] ) ++p_sz;
	while( S[sz] )	   ++sz;

	compute_pie();

	int ans_count = 0;

	int i, matched = 0;
	for( i = 0; i < sz; ++i )
	{
		while( matched && P[ matched ]  != S[i] )
			matched = PI[ matched -1 ];

		if( P[ matched ] == S[i] )
			++matched;
		
		if( matched == p_sz )
		{	
			if( ans_count < 1001 )
				ans[ ans_count ] = i - p_sz + 1;

			++ans_count;
		}
	}

	g << ans_count << "\n";
	
	sz = min( ans_count, 1000 );
	for( i = 0; i < sz; ++i )
		g << ans[ i ] << " ";
	g << "\n";

	return 0;
}