Cod sursa(job #629718)

Utilizator ContraPunctContrapunct ContraPunct Data 3 noiembrie 2011 20:29:15
Problema Potrivirea sirurilor Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

const int B = 67;
const int P = 666013;
const int BB = 71;
const int PP = 666013;

string a,b;

int Bp = 1, BBp = 1;

vector<int> poz;

int x;
int calcB[256];
int calcBB[256];

void ReadData()
{
	ifstream fin("strmatch.in");
	fin>>a>>b;
	
}
void Baza()
{
	int k = a.length();
	for(int i=1; i<k; ++i)
	{
		Bp  = Bp  * B  % P;
		BBp = BBp * BB % PP;
	}
}
void Solve()
{
	int k = a.length(), i;
	int hashb =0, hasha =0;
	int hashb1=0, hasha1=0;
	for (i=0; i < k; i++)
	{
		hasha  = (hasha  * B  + a[i]) % P;
		hasha1 = (hasha1 * BB + a[i]) % PP;
	}

	for (i=0; i < k; i++)
	{
		hashb  = (hashb  * B  + b[i])% P;
		hashb1 = (hashb1 * BB + b[i])% PP;
	}
	if(hasha1 == hashb1)
			{
				poz.push_back(0);
				printf("aaa\n");
			}
			else 
			{
			int ok = 0;
			for(int q = 0; q<k; ++q )
				if(a[q] != b[q])
					ok = 1;
			if( !ok)
				poz.push_back(0);
			}
	
	int j = b.length();
	
	for (int i = 0; i <256; i++)
	{
		calcB[i]  = (i * Bp)  % P;
		calcBB[i] = (i * BBp) % PP;
	}
	for(i=k; i < j;i++)
	{
		hashb  = ((P  + hashb  - calcB [b[i - k]]) * B + b[i])%P;
		hashb1 = ((PP + hashb1 - calcBB[b[i - k]]) * BB + b[i])%PP;
		if( hasha == hashb  && i >= k - 1)
		{		
			if(hasha1 == hashb1)
			{
				poz.push_back(i-k+1);
				printf("aaa\n");
			}
			else 
			{
			int ok = 0, s=i-k+1;
			for(int q = 0; q<k; ++q )
				if(a[q] != b[s+q])
					ok = 1;
			if( !ok)
				poz.push_back(i-k+1);
			}
		}
	}
}

void Afisare()
{
	ofstream fout("strmatch.out");
	int i = (int)poz.size();
	fout<<i<<"\n";
	int j =  min(1000, i);
	for(i=0;i < j ;i++)
		fout<<poz[i]<<" ";
	fout<<"\n";
}
int main()
{
	ReadData();
	Baza();
	Solve();
	Afisare();
	return 0;
}