Cod sursa(job #2390804)

Utilizator vlad_popaVlad Popa vlad_popa Data 28 martie 2019 12:53:23
Problema Potrivirea sirurilor Scor 14
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

#define PMOD1		(666013)
#define PMOD2		(10007)
#define FACTOR		(26)


void rabinKarp(const std::string &strA, const std::string &strB)
{
	int hash1 = 0, hash2 = 0;
	int factorProd1 = 1, factorProd2 = 1;
	for (auto i = 0; i < strA.length(); ++ i) {
		const int curVal = int(strA[i] - 'A'); 
		hash1 = (hash1 * FACTOR + curVal) % PMOD1;
		hash2 = (hash2 * FACTOR + curVal) % PMOD2;
	}
	for (auto i = 0; i < (int)strA.length() - 1; ++ i) {
		factorProd1 = (factorProd1 * FACTOR) % PMOD1;
		factorProd2 = (factorProd2 * FACTOR) % PMOD2;
	}
	
	int hashA1 = hash1;
	int hashA2 = hash2;
	
	std::vector<int> posMatch;
	hash1 = hash2 = 0;
	
	for (auto i = 0; i < strB.length(); ++ i) {
		const int curVal = int(strB[i] - 'A'); 
		int relProd1 = 0, relProd2 = 0;
		if (i >= strA.length()) {
			relProd1 = factorProd1 * int(strB[i-strA.length()] - 'A');
			relProd2 = factorProd2 * int(strB[i-strA.length()] - 'A');
		}
		
		hash1 = ((hash1 - relProd1) * FACTOR + curVal) % PMOD1;
		hash2 = ((hash2 - relProd2) * FACTOR + curVal) % PMOD2;
		
		if (i >= strA.length() && hash1 == hashA1 && hash2 == hashA2) {
			posMatch.push_back(i-strA.length()+1);
		}
	}
	
	std::ofstream out("strmatch.out");
	
	out << posMatch.size() << "\n";
	
	int lim = std::min((int)posMatch.size(), 1000);
	for (auto i = 0; i < lim; ++ i) {
		out << posMatch[i] << " ";
	}
	out << "\n";
		
	out.close();
}


int main ()
{
	/* code */
	std::ifstream in("strmatch.in");
	
	std::string strA, strB;
	
	in >> strA >> strB;
			
	in.close();
	
	rabinKarp(strA, strB);
	
	return 0;
}