Pagini recente » Cod sursa (job #1923261) | Cod sursa (job #3196034) | Cod sursa (job #2760942) | Cod sursa (job #909868) | Cod sursa (job #332846)
Cod sursa(job #332846)
#include<cstdio>
#include<math.h>
#include<string.h>
#define NMAX 2000001
#define MOD 666013
char sir[NMAX], pat[NMAX];
int N, M, PTHASH, FIRSTHASH;
void try_case(int x, int y)
{
int ok=1;
for(int i=1; i<=M; i++)
{
if(sir[i+x-1]!=pat[i])
{
ok=0;
break;
}
}
if(ok)
printf("%d ",x);
}
void make_pat_hash() //face hashul patternului
{
for(int i=1; i<=M; i++)
{
PTHASH=PTHASH*255+pat[i];
PTHASH%=MOD;
FIRSTHASH=FIRSTHASH*255+sir[i];
FIRSTHASH%=MOD;
}
if(FIRSTHASH==PTHASH)
{
try_case(1,M);
}
}
void make_hash(int x, int y, int &lasthash)
{
lasthash-=sir[x-1]*pow(255,M-1);
while(lasthash<0)
{
lasthash+=MOD;
}
lasthash=lasthash*255+sir[y];
lasthash%=MOD;
if(lasthash==PTHASH)
try_case(x,y);
}
int main()
{
freopen("strmatch.in","r",stdin);
freopen("strmatch.out","w",stdout);
scanf("%s",&pat);
M=strlen(pat);
scanf("%s",&sir);
N=strlen(sir);
for(int i = M; i ; --i) pat[i] = pat[i-1];
for(int i = N; i ; --i) sir[i] = sir[i-1];
int lasthash;
make_pat_hash();
lasthash=FIRSTHASH;
for(int i=2; i<=N-M+1; i++)
{
make_hash(i,i+M-1,lasthash);
}
return 0;
}