Pagini recente » Cod sursa (job #2730375) | Cod sursa (job #723647) | Cod sursa (job #1241439) | Cod sursa (job #231332) | Cod sursa (job #1699102)
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int N = 1 + 2e6;
typedef unsigned hash_t;
char buff[2 * N];
hash_t hist_adjust = 1, base = 31;
void set_hist_adjust(int n){
for (hash_t fct = base; n; n >>= 1, fct *= fct)
if ( n & 1 ) hist_adjust *= fct;
}
hash_t push_chr(hash_t val, char A, char B = 'A' - 1){
return val * base + (A - 'A' + 1) - (B - 'A' + 1) * hist_adjust;
}
void rabin_karp(char* text, char* pattern){
hash_t need = 0, val = 0;
vector<int> sol;
int n = strlen(pattern);
for (int i = 0; pattern[i]; i++){
need = push_chr(need, pattern[i]);
val = push_chr(val, text[i]);
}
if (need == val) sol.push_back(0);
set_hist_adjust(n);
for (int i = n; text[i]; i++){
val = push_chr(val, text[i], text[i - n]);
if ( need == val ) sol.push_back(i - n + 1);
}
cout << sol.size() << '\n';
if ( sol.size() > 1000 )
sol.resize(1000);
for (int x : sol)
cout << x << ' ';
cout << '\n';
}
int main(){
freopen("strmatch.in", "r", stdin);
freopen("strmatch.out", "w", stdout);
cin >> buff >> buff + N;
rabin_karp(buff + N, buff);
return 0;
}