Cod sursa(job #2194943)

Utilizator adc98Adam Cristian adc98 Data 14 aprilie 2018 18:30:10
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.35 kb
#include <iostream>
#include <fstream>
#include <cstring>

#define q1 100007
#define q2 100021
#define d 73

using namespace std;
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");

char s[2000001],p[2000001];

int poz[1001],nrElemente;

long long int hashs1,hashs2,pow1,pow2;


long long int putere(long long int a,long  long int b,int q)
{
    if(b==0) return 1;
      else if(b==1) return a % q;
            else if(b%2==0) return (putere(a,b/2,q) * putere(a,b/2,q)) % q;
                  else return (a * putere(a,b/2,q) * putere(a,b/2,q)) % q;
}

void calculHash(long long int poz)
{
    hashs1= ( (hashs1-s[poz]*pow1)*d + s[poz+strlen(p)] ) % q1;
    if(hashs1<0) hashs1+=q1;
    hashs2= ( (hashs2-s[poz]*pow2)*d + s[poz+strlen(p)] ) %q2;
    if(hashs2<0) hashs2+=q2;
}

int main()
{
    fin.getline(p,2000001);
    fin.getline(s,2000001);

    int lg_p=strlen(p);
    int lg_s=strlen(s);

   if(lg_p > lg_s)
        {
         fout<<0;
         return 0;
        }

    long long int hashp1=0,hashp2=0;

    for(int i=0;i<lg_p;++i)
        {
         hashs1=(hashs1*d+s[i])%q1;
         hashs2=(hashs2*d+s[i])%q2;
         hashp1=(hashp1*d+p[i])%q1;
         hashp2=(hashp2*d+p[i])%q2;
        }

    pow1=putere(d,lg_p-1,q1);
    pow2=putere(d,lg_p-1,q2);

    /*pow=1;
    for(int i=0;i<lg_p-1;++i)
        {
         pow=(pow*d)%q;
        }*/

    /*pow=1;
    for(int i=lg_p-1;i>=0;--i)
        {
         hashs=( hashs + ((int) (s[i]) * pow) % q) % q;
         hashp=( hashp + ((int) (p[i]) * pow) % q ) %q;
         if(i>0) pow=(pow * d) % q;
        }*/


    for(int i=0;i<=lg_s-lg_p;++i)
        {
         if(hashs1==hashp1 && hashs2==hashp2)
            {
              if(nrElemente<1000) poz[nrElemente++]=i;
               else nrElemente++;
            }
         /*if(hashs==hashp)
            {
             int j=0;
             for(j=0;j<lg_p;++j)
                {
                 if(p[j]!=s[i+j]) break;
                }
             if(j==lg_p)
                {
                 if(nrElemente<1000) poz[nrElemente++]=i;
                  else nrElemente++;
                }
            }*/
         calculHash(i);
        }
    fout<<nrElemente<<"\n";
    if(nrElemente>1000) nrElemente=1000;
    for(int i=0;i<nrElemente;++i) fout<<poz[i]<<" ";
    return 0;
}