Cod sursa(job #2698432)

Utilizator VladNANegoita Vlad-Andrei VladNA Data 22 ianuarie 2021 09:43:09
Problema Potrivirea sirurilor Scor 92
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>
#define LMAX 2000000

using namespace std;

///'A' corespunde lui 0

const int p1=688741, b1=137;
const int p2=688889, b2=139;

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

char A[5+LMAX], B[5+LMAX];

vector<int>rasp;

int main()
{
    int n,m;
    in.getline(A,LMAX+2);
    in.getline(B,LMAX+2);
    n=strlen(A);
    m=strlen(B);
    if(n>m)
    {
        out<<"0";
        return 0;
    }
    long long exp1=1,exp2=1,hash1B=0,hash2B=0,hash1A=0,hash2A=0,cnt=0;
    for(int i=0;i<n;i++)
    {
        hash1A=(hash1A*b1+(A[i]-'A'))%p1;
        hash2A=(hash2A*b2+(A[i]-'A'))%p2;
        hash1B=(hash1B*b1+(B[i]-'A'))%p1;
        hash2B=(hash2B*b2+(B[i]-'A'))%p2;
        if(i!=0)
        {
            exp1=(exp1*b1)%p1;
            exp2=(exp2*b2)%p2;
        }
    }
    ///la final exp1=b1^(n-1)
    ///la final exp2=b2^(n-1)
    if(hash1A==hash1B && hash2A==hash2B)
    {
        cnt++;
        rasp.push_back(0);
    }
    for(int i=1; i<m-n+1; i++)
    {
        hash1B=(hash1B-((B[i-1]-'A')*exp1)%p1+p1)%p1;
        hash2B=(hash2B-((B[i-1]-'A')*exp2)%p2+p2)%p2;
        hash1B=(hash1B*b1)%p1;
        hash2B=(hash2B*b2)%p2;
        hash1B=(hash1B+(B[i+n-1]-'A'))%p1;
        hash2B=(hash2B+(B[i+n-1]-'A'))%p2;
        if(hash1A==hash1B && hash2A==hash2B)
        {
            cnt++;
            if(rasp.size()<1000)
                rasp.push_back(i);
        }
    }
    out<<cnt<<'\n';
    for(int i=0; i<1000 && i<rasp.size();i++)
        out<<rasp[i]<<' ';
    return 0;
}