Pagini recente » Cod sursa (job #1867117) | Cod sursa (job #2151885) | Cod sursa (job #2072736) | Cod sursa (job #2903497) | Cod sursa (job #2707633)
#include<fstream>
#include<string.h>
#include<string>
#include<vector>
#define MOD 1010012359
#define d 75
#define lim 2000005
using namespace std;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
char txt[lim], pat[lim];
vector<int> ans;
void rabin_karp(const char* pat, const char* txt)
{
int M = strlen(pat);
int N = strlen(txt);
if (M > N)
{
return ;
}
int i, j;
int hashpat = 0;
int hashtxt = 0;
int h = 1;
for (int i = 0; i < M; i++)
{
h = (h * d) % MOD;
hashpat = (d * hashpat + pat[i]) % MOD;
hashtxt = (d * hashtxt + txt[i]) % MOD;
}
for ( i = 0; i <= N - M; i++)
{
if (hashpat == hashtxt)
{
//for ( j = 0; j < M; j++)
//if (txt[i + j] != pat[j])
//break;
//if (j == M)
ans.push_back(i);
}
if (i < N - M)
{
hashtxt = (d * (hashtxt - txt[i] * h) + txt[i + M]) % MOD;
if (hashtxt < 0)
hashtxt += MOD;
}
else
break;
}
}
int main()
{
ios_base::sync_with_stdio(false);
f.tie(0);
f.getline(pat, lim);
f.getline(txt, lim);
rabin_karp(pat, txt);
g << ans.size() << '\n';
int nr = ans.size();
if (nr > 1000)
nr = 1000;
for (int i = 0; i < nr; i++)
g << ans[i] << " ";
return 0;
}