Pagini recente » Rating Tudor Oprescu (turnen) | Rating Stroe Andra-Nicoleta (NuSuntEu) | Cod sursa (job #1299558) | Cod sursa (job #3124015) | Cod sursa (job #2390804)
#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;
}