Pagini recente » Cod sursa (job #1319887) | Cod sursa (job #422107) | Cod sursa (job #2676384) | Cod sursa (job #1071462) | Cod sursa (job #1710632)
#include <fstream>
#include <string>
#include <vector>
using namespace std;
ifstream f{ "strmatch.in" };
ofstream q{ "strmatch.out" };
#define PRIME 101
#define MOD 22801763489
long long ReHash(const long long& oldHash, const char& oldChar, const char& newChar, const long long& pow ) {
return ((((oldHash - oldChar) / PRIME) + (newChar * pow)) % MOD);
}
void RabinKarp(const string& pattern, const string& text) {
int n = (int)text.size();
int m = (int)pattern.size();
long long patternHash = 0;
long long searchHash = 0;
long long pow = 1;
int count = 0;
vector <int> pozitii;
for (size_t i = 0; i < m; i++) {
patternHash = (patternHash + pow * pattern[i]) % MOD;
searchHash = (searchHash + pow * text[i]) % MOD;
pow = (pow * PRIME) % MOD;
}
pow /= PRIME;
if (patternHash == searchHash) {
bool ok = true;
for (size_t j = 0; j < m && ok == true; j++) {
if (pattern[j] != text[j]) ok = false;
}
if (ok) count = 1, pozitii.push_back(0);
}
for (size_t i = m; i < n; i++) {
searchHash = ReHash(searchHash, text[i - m], text[i], pow);
if (patternHash == searchHash) {
bool ok = true;
for (size_t j = i - m + 1, k = 0; k < m && ok == true; j++, k++) {
if (pattern[k] != text[j]) ok = false;
}
if (ok) count++;
if (ok && count <= 1000) pozitii.push_back((int)(i - m + 1));
}
}
q << count << "\n";
for (auto& poz : pozitii) q << poz << " ";
}
int main() {
string pattern, text;
f >> pattern >> text;
RabinKarp(pattern, text);
f.close();
q.close();
}