Cod sursa(job #2032947)

Utilizator robuvedVictor Robu robuved Data 5 octombrie 2017 21:44:31
Problema Potrivirea sirurilor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <vector>
using namespace std;

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

const int MAX = 2e6 + 1;
const int p = 100003;
const int q = 100007;
const int B = 73;
vector<int> occ;
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(char* T, int N, char* P, int M)
{
	if (M > N)
		return vector<int>();
	int p_hash = 0;
	int p_hash2 = 0;

	int t_hash = 0;
	int t_hash2 = 0;

	int B_m = 1;
	int B_m2 = 1;

	for (int i = 0; i < M; i++)
	{
		p_hash = (p_hash * B + P[i]) % p;
		p_hash2 = (p_hash2 * B + P[i]) % q;

		t_hash = (t_hash * B + T[i]) % p;
		t_hash2 = (t_hash2 * B + T[i]) % q;
		if (i != 0)
		{
			B_m = (B_m * B) % p;
			B_m2 = (B_m2 * B) % q;
		}
	}

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

	for (int i = M; i < N; i++)
	{
		t_hash = ((((t_hash - (T[i - M] * B_m)%p + p) ) * B)%p + T[i])%p;
		t_hash2 = ((((t_hash2 - (T[i - M] * B_m2) % q + q) ) * B) % q + T[i]) % q;

		if (t_hash == p_hash && p_hash2 == t_hash2)
		{
			//if (Find(T, i - M + 1, i, P))
			{
				occ.push_back(i - M + 1);
				if (occ.size() == 1000)
					break;
			}
		}
	}
	return occ;
}
int main()
{
	char *A = new char[MAX];
	char *Bs = new char[MAX];
	in >> A >> Bs;
	RabinKarp(Bs, strlen(Bs), A, strlen(A));
	out << occ.size() << '\n';
	for (int i = 0; i< occ.size(); i++)
	{
		out << occ[i] << ' ';
	}
}