Pagini recente » Cod sursa (job #717288) | Cod sursa (job #1469613) | Cod sursa (job #691254) | Cod sursa (job #359248) | Cod sursa (job #2874998)
/*
Rezolvare problemei Strmatch folosinf algoritmul Rabin-Karp
adaptat la litere mari si cifre
*/
#include <bits/stdc++.h>
#include <string>
#define prime 101
using namespace std;
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
int firstHash(string text);
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int cnt = 0;
vector<int> potriviri;
string text, pattern;
fin >> pattern >> text;
int i, j;
int n = pattern.length(), m = text.length();
int hash = firstHash(pattern);
string firstWindow = text.substr(0, n);
int windowHash = firstHash(firstWindow);
int h = 1;
for(int i = 0; i < n - 1; i++)
h = (h * 256) % prime;
for(i = 0; i <= m - n; i++) {
if( hash == windowHash ) {
for(j = 0; j < n; j++)
if( pattern[j] != text[i + j] )
break;
if( j == n ) {
if( cnt <= 1000 )
potriviri.push_back(i);
cnt++;
}
}
if( i < m - n ) {
windowHash = (256*(windowHash - text[i]*h) + text[i + n]) % prime;
if(windowHash < 0)
windowHash += prime;
}
}
fout << cnt << '\n';
for(i = 0; i < min(1000, cnt); i++)
fout << potriviri[i] << " ";
return 0;
}
int firstHash(string text) {
int hash = 0;
int n = text.length();
for(int i = 0; i < n; i++)
hash = (256 * hash + text[i]) % prime;
return hash;
}