Pagini recente » Cod sursa (job #2856936) | Cod sursa (job #2094696) | Cod sursa (job #1246563) | Cod sursa (job #354007) | Cod sursa (job #2468844)
#include <bits/stdc++.h>
#define MAXLEN (int)(2e6 + 5)
#define d 131LL
using namespace std;
char pattern[MAXLEN], text[MAXLEN];
int matchCount, matches[MAXLEN];
void rkSearch(char pat[], char txt[], long long q)
{
int pLen = strlen(pat);
int nLen = strlen(txt);
int i;
int h = 1; //value of h would be pow(d, pLen-1) % q
for (i = 0; i < pLen - 1; ++i)
h = (d * h) % q;
//calculate the hash value of pattern and first window of text
int pHash = 0, tHash = 0;
for (i = 0; i < pLen; i++)
{
pHash = (d * pHash + pat[i]) % q;
tHash = (d * tHash + txt[i]) % q;
}
//slide the pattern over text one by one
for (i = 0; i <= nLen - pLen; ++i)
{
//check the hash values of current window of text and pattern
//if the hash values match then only check for characters on by one
if (pHash == tHash)
{
//check for characters one by one
matches[++matchCount] = i;
}
//calculate hash value for next window of text
//remove leading digit, add trailing digit
if (i < nLen - pLen)
{
tHash = (d * (tHash - 1LL*txt[i]*h) + txt[i + pLen]) % q;
//we might get negative value of t
//we should convert it to positive
if (tHash < 0)
tHash += q;
}
}
}
int main()
{
freopen("strmatch.in", "r", stdin);
freopen("strmatch.out", "w", stdout);
scanf("%s %s", pattern, text);
rkSearch(pattern, text, 1000000007LL);
printf("%d\n", matchCount);
int minOut = min(matchCount, 1000);
for (int i = 1; i <= minOut; ++i)
printf("%d ", matches[i]);
printf("\n");
return 0;
}