Cod sursa(job #2482339)

Utilizator altcontnoualt cont altcontnou Data 28 octombrie 2019 09:40:37
Problema Potrivirea sirurilor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

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

const int mod1=1999993, mod2=1999979;

char sir1[2000005], sir2[2000005];
int hash11, hash12, hash21, hash22, lungime, putere1, putere2;
int rez[1010];
int nr_rez, l2;

int create_hash(char *s, int l, int mod)
{
    int put=1;
    int rez=0;
    for (int i=l-1; i>=0; --i)
    {
        rez+=(s[i]-'A'+1)*put;
        put*=27;
        put%=mod;
        rez%=mod;
    }
    return rez;
}

int ridicare_putere(int x, int putere, int mod)
{
    int a=x, b=1;
    while (putere)
    {
        if (putere&1)
        {
            b*=a;
            b%=mod;
        }
        a*=a;
        a%=mod;
        putere>>=1;
    }
    return b;
}

void solve()
{
    if (hash11==hash21 && hash12 == hash22)
    {
        rez[++nr_rez]=0;
    }
    l2=strlen(sir2);
    int auxh21, auxh22;
    for (int i=1; i<l2; ++i)
    {
        auxh21=hash21-(sir2[i-1]-'A'+1)*putere1;
        while (auxh21<0)
            auxh21+=mod1;
        auxh21*=27;
        auxh21%=mod1;
        auxh21+=(sir2[i+lungime-1]-'A'+1);


        auxh22=hash22-(sir2[i-1]-'A'+1)*putere2;
        while (auxh22<0)
            auxh22+=mod2;
        auxh22*=27;
        auxh22%=mod2;
        auxh22+=(sir2[i+lungime-1]-'A'+1);

        hash21=auxh21;
        hash22=auxh22;

        if (hash11==hash21 && hash12 == hash22)
        {
            if (nr_rez<1000)
                rez[++nr_rez]=i;
            else
                ++nr_rez;
        }
    }
}

void afisare()
{
    f << nr_rez << '\n';
    int mini=min(nr_rez,1000);
    for (int i=1; i<=mini; ++i)
        g << rez[i] <<' ';
}

int main()
{
    f >> sir1 >> sir2;
    lungime=strlen(sir1);
    putere1=ridicare_putere(27,lungime-1, mod1);
    putere2=ridicare_putere(27,lungime-1, mod2);
    hash11=create_hash(sir1,lungime,mod1);
    hash12=create_hash(sir1,lungime,mod2);
    hash21=create_hash(sir2,lungime,mod1);
    hash22=create_hash(sir2,lungime,mod2);

    solve();
    afisare();
    return 0;
}