Cod sursa(job #3003553)

Utilizator laurentiu.maticaMatica Laurentiu-Andrei laurentiu.matica Data 15 martie 2023 19:52:31
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <cstring>
using namespace std;
ifstream cin("strmatch.in");
ofstream cout("strmatch.out");
#define MOD1 100007
#define MOD2 100021
#define PRIM 216
int match[2000005];
char a[2000001];
char b[2000001];
void rbk(char text[],char sablon[])
{
    int na=strlen(text);
    int nb=strlen(sablon);

    int p1=1,p2=1;
    int hashB1=0,hashB2=0;
    for(int i=0; i<nb; i++)
    {
        hashB1=(1LL*hashB1*PRIM + sablon[i])%MOD1;
        hashB2=(1LL*hashB2*PRIM + sablon[i])%MOD2;
        if(i)
        {
            p1=(1LL*p1*PRIM)%MOD1;
            p2=(1LL*p2*PRIM)%MOD2;
        }
    }
    if(nb>na)
    {
        cout << 0;
        return;
    }
    int hash1=0,hash2=0;
    for(int i=0; i<nb; i++)
    {
        hash1=(1LL*hash1*PRIM+text[i])%MOD1;
        hash2=(1LL*hash2*PRIM+text[i])%MOD2;
    }
    int cnt=0;
    if(hash1 == hashB1 && hashB2 && hash2)
        match[cnt++]=0;
    for(int i=nb; i<na; i++)
    {
        hash1=((hash1-(1LL*text[i-nb]*p1)%MOD1 + MOD1) * PRIM + text[i])%MOD1;
        hash2=((hash2-(1LL*text[i-nb]*p2)%MOD2 + MOD2) * PRIM + text[i])%MOD2;
        if(hash1 == hashB1 && hashB2 && hash2)
            match[cnt++]=i-nb+1;
    }
    cout << cnt << '\n';
    for(int i = 0; i < cnt && i<1000;i++)
        cout << match[i] << ' ';
}
int main()
{
    cin.getline(a,2000001);
    cin.getline(b,2000001);
    rbk(b,a);
    return 0;
}