Pagini recente » Cod sursa (job #148769) | Cod sursa (job #1289458) | Cod sursa (job #1736714) | Cod sursa (job #71518) | Cod sursa (job #3318078)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 2000005;
const long long BASE = 100;
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 + powers[n-i-1] * (s[i] - HASHER)) % MOD;
return h;
}
vector<int> RabinKarp(const char a[NMAX], const char b[]) {
vector<int> positions;
int n = strlen(a), m = strlen(b);
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 = (current_hash - powers[n - 1] * (b[i - n] - HASHER)) % MOD;
if (current_hash < 0) current_hash += MOD;
current_hash = (current_hash * BASE) % MOD;
current_hash = (current_hash + (b[i] - HASHER)) % MOD;
if (current_hash == hash_A)
positions.push_back(i);
}
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 < (int)ans.size(); i++)
cout << ans[i] - strlen(A) + 1 << " ";
cout << "\n";
return 0;
}