Pagini recente » Borderou de evaluare (job #1708258) | Cod sursa (job #2720499) | Cod sursa (job #2766284) | Cod sursa (job #3259431) | Cod sursa (job #2390820)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#define PMOD1 (666013)
#define PMOD2 (10007)
#define FACTOR (256)
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]);
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]);
int relProd1 = 0, relProd2 = 0;
if (i >= strA.length()) {
relProd1 = factorProd1 * int(strB[i-strA.length()]);
relProd2 = factorProd2 * int(strB[i-strA.length()]);
}
hash1 = ((((hash1 - relProd1) % PMOD1 + PMOD1) * FACTOR) + curVal) % PMOD1;
hash2 = ((((hash2 - relProd2) % PMOD2 + PMOD2) * 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;
}