Pagini recente » Cod sursa (job #2684974) | Cod sursa (job #834386) | Cod sursa (job #542658) | Cod sursa (job #3313514) | Cod sursa (job #3318135)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 2000005;
const long long BASE = 131;
const long long MOD = 1000000007;
const char HASHER = '0';
char A[NMAX], B[NMAX];
long long powers[NMAX];
void PrecomputePowers(int n) {
powers[0] = 1;
for (int i = 1; i <= n; i++)
powers[i] = (powers[i - 1] * BASE) % MOD;
}
long long HashEntireString(const char s[], int n) {
long long h = 0;
for (int i = 0; i < n; i++)
h = (h + 1LL * powers[n - i - 1] * (s[i] - HASHER)) % MOD;
return h;
}
long long getNextHash(long long current_hash, int n, char oldChar, char newChar) {
current_hash = (current_hash - (1LL * powers[n - 1] * (oldChar - HASHER))) % MOD;
if (current_hash < 0) current_hash += MOD;
current_hash = (current_hash * BASE) % MOD;
current_hash = (current_hash + (newChar - HASHER)) % MOD;
return current_hash;
}
vector<int> RabinKarp(const char a[], const char b[]) {
vector<int> positions;
int n = strlen(a), m = strlen(b);
if (n > m) return positions;
long long hash_A = HashEntireString(a, n);
long long current_hash = HashEntireString(b, n);
if (hash_A == current_hash)
positions.push_back(0);
for (int i = n; i < m; i++) {
current_hash = getNextHash(current_hash, n, b[i - n], b[i]);
if (current_hash == hash_A)
positions.push_back(i - n + 1);
}
return positions;
}
int main() {
freopen("strmatch.in", "r", stdin);
freopen("strmatch.out", "w", stdout);
cin >> A >> B;
PrecomputePowers(strlen(A) + 1);
vector<int> ans = RabinKarp(A, B);
cout << ans.size() << "\n";
for (int i = 0; i < min((int)ans.size(), 1000); i++)
cout << ans[i] << " ";
cout << "\n";
return 0;
}