Pagini recente » Cod sursa (job #1726779) | Cod sursa (job #2685574) | Cod sursa (job #1172165) | Cod sursa (job #973323) | Cod sursa (job #2707621)
#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);
int i, j;
int hashpat = 0;
int hashtxt = 0;
int h = 1;
for (int i = 1; i <= M - 1; i++)
h = (h * d) % MOD;
for (int i = 0; i < M; i++)
{
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()
{
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;
}