Pagini recente » Cod sursa (job #1588972) | Cod sursa (job #1695038) | Cod sursa (job #1944872) | Cod sursa (job #371552) | Cod sursa (job #2707637)
#include<fstream>
#include<string.h>
#include<string>
#include<vector>
#define MOD 100007
#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++)
{
hashpat = (d * hashpat + pat[i]) % MOD;
hashtxt = (d * hashtxt + txt[i]) % MOD;
h = (h * d) % 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;
}