Cod sursa(job #2284506)

Utilizator AndreiGSGhiurtu Andrei AndreiGS Data 17 noiembrie 2018 11:19:42
Problema Potrivirea sirurilor Scor 14
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

struct Hash
{
    int n, m, power, hash1;
    void init(char *s, int len)
    {
        power=1, hash1=0;
        for(int i=len-1; i>=0; --i)
        {
            hash1=(hash1+(power*s[i])%m)%m;
            if(i)
                power=(power*n)%m;
        }
    }
    void roll(char toRemove, char toAdd)
    {
        hash1=(((hash1-(toRemove*power)%m+m)*n)%m+toAdd)%m;
    }
};


const int NMAX=2000000;
char p[NMAX], t[NMAX];

int main()
{

    int n, m;
    int poz[1000], nrpoz=0;

    ifstream f("strmatch.in");
    ofstream g("strmatch.out");

    f>>p>>t;
    n=strlen(p), m=strlen(t);
    Hash phash{31, 40099}, thash{31, 40099};
    Hash phash2{53, 319993}, thash2{53, 319993};
    phash.init(p, n);
    thash.init(t, n);
    phash2.init(p, n);
    thash2.init(t, n);
//
    if(phash.hash1==thash.hash1 && phash2.hash1==thash2.hash1)
        poz[nrpoz++]=0;
    for(long long i=n; i<m; i++)
    {
        thash.roll(t[i-n], t[i]);
        thash2.roll(t[i-n], t[i]);
        if(phash.hash1==thash.hash1 && phash2.hash1==thash2.hash1)
        {
            if(nrpoz<=1000)
                poz[++nrpoz]=(i-n+1);
            else
                nrpoz++;
        }
    }
    g<<nrpoz<<"\n";
    if(nrpoz>1000)
        nrpoz=1000;
    for(int i=0; i<nrpoz; i++)
        g<<poz[i]<<" ";


    return 0;
}