Cod sursa(job #2032974)

Utilizator robuvedVictor Robu robuved Data 5 octombrie 2017 22:12:21
Problema Potrivirea sirurilor Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;

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

const int MAX = 2e6 + 1;
const int p = 100007;
const int q = 100021;
const int B = 73;
vector<int> occ;
bool Find(char*T, int start, int end, char* P)
{
	for (int i = start; i <= end; i++)
	{
		if (T[i] != P[i - start])
		{
			return false;
		}
	}
	return true;
}
void RabinKarp(char* T, int N, char* P, int M)
{
	if (M > N)
	{
		out << 0;
		return;
	}
	int p_hash1 = 0;
	int p_hash2 = 0;

	int t_hash1 = 0;
	int t_hash2 = 0;

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

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

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

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

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

}