Cod sursa(job #3003596)

Utilizator laurentiu.maticaMatica Laurentiu-Andrei laurentiu.matica Data 15 martie 2023 20:07:52
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 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);
    if(nb>na)
    {
        cout << 0;
        return;
    }
    int p1=1,p2=1;
    int hashB1=0,hashB2=0;
    int hash1=0,hash2=0;
    for(int i=0; i<nb; i++)
    {
        hashB1=(hashB1*PRIM + sablon[i])%MOD1;
        hashB2=(hashB2*PRIM + sablon[i])%MOD2;
        hash1=(hash1*PRIM+text[i])%MOD1;
        hash2=(hash2*PRIM+text[i])%MOD2;
        if(i)
        {
            p1=(p1*PRIM)%MOD1;
            p2=(p2*PRIM)%MOD2;
        }
    }
    int cnt=0;
    if(hash1 == hashB1 && hashB2 && hash2)
        match[cnt++]=0;
    for(int i=1; i<=na-nb; i++)
    {
        hash1=(((hash1-(text[i-1]*p1))%MOD1+MOD1)*PRIM+text[i+nb-1])%MOD1;
        hash2=(((hash2-(text[i-1]*p2))%MOD2+MOD2)*PRIM+text[i+nb-1])%MOD2;
        if(hash1 == hashB1 && hashB2 && hash2)
            match[cnt++]=i;
    }
    cout << cnt << '\n';
    if(cnt>1000)
        for(int i=0;i<1000;i++)
            cout << match[i] << ' ';
    else
        for(int i=0;i<cnt;i++)
            cout << match[i] << ' ';
}
int main()
{
    cin.getline(a,2000001);
    cin.getline(b,2000001);
    rbk(b,a);
    return 0;
}