Cod sursa(job #1812965)

Utilizator rangalIstrate Sebastian rangal Data 22 noiembrie 2016 16:31:17
Problema Potrivirea sirurilor Scor 14
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <cstdio>
#include <iostream>
#include <cstring>
#define lgmax 2000003
#define in "strmatch.in"
#define out "strmatch.out"
#define base 62 //26 (a-z) 26 (A-Z) 10 (0-9)
#define mod 666013
#define mod2 666017

typedef unsigned long long ull;

using namespace std;

ull Mx,Mx2;
char A[lgmax],B[lgmax];
int ct=0,rez[1003];

inline void HashSrch(char *v,const ull ha,const ull ha2 ,char *w,ull &hb,ull &hb2,int poz,int m)
{
    if(ha==hb && ha2==hb2)
    {
        ++ct;
        if(ct<=1000) rez[ct]=poz;
    }

    hb=( (hb - Mx*w[0]%mod +mod) * base +w[m] ) %mod;
    hb2=( (hb2 - Mx2*w[0]%mod2 +mod2) * base +w[m] ) %mod2;
}

int main()
{
    freopen(in,"r",stdin);
    freopen(out,"w",stdout);

    scanf("%s %s",A,B);

    int m=strlen(A);
    int n=strlen(B);

    if(m>n)
    {
        printf("0\n");
        return 0;
    }

    ull ha,ha2,hb,hb2;
    ha=ha2=hb=hb2;

    for(int i=0; i<m; ++i)
    {
        ha=(ha*base +A[i])%mod;
        ha2=(ha2*base +A[i])%mod2;
        hb=(hb*base +B[i])%mod;
        hb2=(hb2*base +B[i])%mod2;

        if(i!=0) //Mx = base^(m-1) %mod , Mx2 =... %mod2
        {
            Mx=(Mx*base)%mod;
            Mx2=(Mx2*base)%mod2;
        }
    }

    for(int i=0; i<=n-m; ++i)
        HashSrch(A,ha,ha2,B+i,hb,hb2,i,m);

   printf("%d\n",ct);
    for(int i=1; i<=min(1000,ct); ++i)
        printf("%d ",rez[i]);

    fclose(stdin); fclose(stdout);
    return 0;
}