Cod sursa(job #2675499)

Utilizator mvcl3Marian Iacob mvcl3 Data 21 noiembrie 2020 21:17:30
Problema Potrivirea sirurilor Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>

const int base = 256;
const int mod = 10007;

std::vector<int> rabin_karp(const std::string& A, const std::string& B)
{

	if (A.length() > B.length())
		return {};

	if (A.length() == B.length())
	{
		if (A == B)
			return { 0 };

		return {};
	}


	std::vector<int> sol;
	
	int refHash = 0;
	int currHash = 0;
	for (int i = 0; i < A.length(); ++i)
	{
		refHash = (refHash * base + A[i]) % mod;
		currHash = (currHash * base + B[i]) % mod;
	}

	int h = 1;
	for (int i = 0; i < A.length() - 1; ++i)
	{
		h = (h * base) % mod;
	}

	for (int i = 0; i <= B.length() - A.length(); ++i)
	{
		if(currHash == refHash && A == B.substr(i, A.length()))
		{
			sol.push_back(i);
		}

		currHash = (((currHash - h * B[i]) * base + B[i + A.length()]) % mod + mod) % mod;
	}

	return std::move(sol);
}



int main()
{
	std::ifstream in("strmatch.in");
	std::ofstream out("strmatch.out");

	std::string A, B;
	in >> A >> B;

	auto sol = rabin_karp(A, B);
	
	out << sol.size() << std::endl;
	for (size_t i = 0; i < std::min(sol.size(), size_t(1000)); ++i)
	{
		out << sol[i] << ' ';
	}


	return 0;
}