Cod sursa(job #2032762)

Utilizator robuvedVictor Robu robuved Data 5 octombrie 2017 17:35:19
Problema Potrivirea sirurilor Scor 14
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <string>
#include <vector>
using namespace std;

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

#define p 1000000007
#define B 256
bool Find(string T, int start, int end, string P)
{
	for (int i = start; i <= end; i++)
	{
		if (T[i] != P[i - start])
		{
			return false;
		}
	}
	return true;
}
vector<int> RabinKarp(string T, string P)
{
	long long p_hash = 0;
	long long t_hash = 0;
	int B_m = 1;
	vector<int> occ;
	for (int i = 0; i < P.size(); i++)
	{
		p_hash = (p_hash * B + P[i]) % p;
		t_hash = (t_hash * B + T[i]) % p;
	}
	for (int i = 0; i < P.size() - 1; i++)
	{
			B_m = (B_m * B) % p;
	}

	if (p_hash == t_hash && Find(T, 0, P.size() -1 , P))
	{
		occ.push_back(0);
	}

	for (int i = P.size(); i < T.size(); i++)
	{
		t_hash = ((((t_hash - (T[i - P.size()] * B_m)%p + p)%p ) * B)%p + T[i])%p;
		if (t_hash == p_hash)
		{
			if (Find(T, i - P.size() + 1, i, P))
			{
				occ.push_back(i - P.size() + 1);
			}
		}
	}
	return occ;
}
int main()
{
	string A, Bs;
	in >> A >> Bs;
	vector<int> occ = RabinKarp(Bs, A);
	out << occ.size() << endl;
	for (int i = 0; i< occ.size() && i < 1000; i++)
	{
		out << occ[i] << ' ';
	}
}