Pagini recente » Cod sursa (job #2513424) | Cod sursa (job #80113) | Monitorul de evaluare | Cod sursa (job #2114111) | Cod sursa (job #1710638)
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
ifstream f{ "strmatch.in" };
ofstream q{ "strmatch.out" };
#define PRIME 101
#define MOD 2000099
int ReHash(const int& oldHash, const char& oldChar, const char& newChar, const int& pow ) {
return ((((oldHash - (int)oldChar) / PRIME) + ((int)newChar * pow)) % MOD);
}
bool checkEqual(const string& str1, const int& starti, const int& endi, const string& str2, const int&startf, const int& endf) {
if (endf - startf != endi - starti) return false;
for (int i = starti, j = startf; i <= endi && j <= endf; i++, j++) {
if (str1[i] != str2[j]) return false;
}
return true;
}
void RabinKarp(const string& pattern, const string& text) {
int n = (int)text.size();
int m = (int)pattern.size();
int patternHash = 0;
int searchHash = 0;
int pow = 1;
vector <int> pozitii;
for (int i = 0; i < m; i++) {
patternHash = (patternHash + pow * pattern[i]) % MOD;
searchHash = (searchHash + pow * text[i]) % MOD;
pow = (pow * PRIME) % MOD;
}
pow /= PRIME;
for (int i = 1; i <= n - m + 1; i++) {
if (patternHash == searchHash) {
if (checkEqual(text, i - 1, i + m - 2, pattern, 0, m - 1) == true) {
pozitii.push_back((int)(i - 1));
}
}
if (i < n - m + 1 )searchHash = ReHash(searchHash, text[i - 1], text[i + m - 1], pow);
}
q << pozitii.size() << "\n";
int mins = min((int)pozitii.size(), 1000);
for (int i = 0; i < mins; i++) q << pozitii[i] << " ";
}
int main() {
string pattern, text;
f >> pattern >> text;
RabinKarp(pattern, text);
f.close();
q.close();
}