Cod sursa(job #629550)

Utilizator ContraPunctContrapunct ContraPunct Data 3 noiembrie 2011 14:46:11
Problema Potrivirea sirurilor Scor 16
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

const int B = 67;
const int P = 666013;
const int BB = 91;
const long PP = 1000007;

string a,b;

vector<int> Bp;
vector<int> BBp;
vector<int> poz;
int x;
void ReadData()
{
	ifstream fin("strmatch.in");
	fin>>a>>b;
}
void Baza()
{
	int k = a.length(), nr;
	Bp.push_back(1);
	BBp.push_back(1);
	for(int i=1;i<=k;i++)
	{
		nr = (long long) Bp[i-1] * B % P;
		Bp.push_back(nr);
		
		nr = (long long) BBp[i-1] * BB %PP;
		BBp.push_back(nr);
	}
}
void Solve()
{
	int k = a.length(),i;
	long long hashb=0,hasha=0;
	long long hashb1=0, hasha1=0;
	for (i=0; i < k; i++)
	{
		hasha  = (hasha  + (long long) a[i] *  Bp[k-1-i]) % P;
		hasha1 = (hasha1 + (long long) a[i] * BBp[k-1-i]) % PP;
	}
	for (i=0; i < k; i++)
	{
		hashb  = ( hashb  + (long long) b[i] * Bp[k-1-i]) % P;
		hashb1 = ( hashb1 + (long long) b[i] * BBp[k-1-i]) % PP;
	}
	int ok = 0;
	if( hasha == hashb && hasha1 == hashb1)
	{
		//poz.push_back(0);
		for(i=0;i<k ;i++)
			if(a[i]!=b[i])
				ok = 1;
		if( ok == 0 )
		{
			poz.push_back(0);
		}
	}
	int j = b.length();
	for(i=k; (i< j);++i)
	{
		hashb  = (P  + (hashb -  (long long) b[i-k] * Bp[k-1] % P) * Bp[1]  + b[i])%P;
		hashb1 = (PP + (hashb1 - (long long) b[i-k] * BBp[k-1] % PP) * BBp[1] + b[i])%PP;
		if( hasha == hashb && hasha1 == hashb1)
		{
		//verific;
			//poz.push_back(i-k+1);
			ok = 0;
			for(int q = 0; q<k; ++q )
				if(a[q] != b[i-k+q+1])
					ok = 1;
			if( ok == 0 )
			{
				poz.push_back(i-k+1);
			}
		}
	}

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