Cod sursa(job #2032980)

Utilizator robuvedVictor Robu robuved Data 5 octombrie 2017 22:21:06
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 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;
int occ[MAX];

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;
		}
	}

	int count = 0;
	if (p_hash1 == t_hash1 && p_hash2 == t_hash2 )
	{
		occ[0] = 1, count++;
	}

	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)
		{
			{
				occ[i - M + 1] = 1;
				count++;
			}
		}
	}
	out << count << '\n';
	count = min(1000, count);

	for (int i = 0; i < N && count; i++)
	{
		if (occ[i])
		{
			out << i << ' ';
			count--;
		}
	}
}
int main()
{
	char *A = new char[MAX];
	char *Bs = new char[MAX];
	in >> A >> Bs;
	RabinKarp(Bs, strlen(Bs), A, strlen(A));

}