Cod sursa(job #2770113)

Utilizator LucaMihaiLM10Luca Ilie LucaMihaiLM10 Data 19 august 2021 14:16:13
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <stdio.h>

#define MAX_N 2000000
#define MAX_SOL 1000
#define MOD1 100007
#define MOD2 100021
#define SIGMA 256

int text[MAX_N], pat[MAX_N], sol[MAX_SOL];
int main() {
    FILE *fin, *fout;
    char ch;
    int n, m, nrSol, hashPat1, hashPat2, hashText1, hashText2, p1, p2, i;
    fin = fopen( "strmatch.in", "r" );

    ch = fgetc( fin );
    m = 0;
    while ( ch != '\n' ) {
        pat[m] = ch;
        m++;
        ch = fgetc( fin );
    }

    ch = fgetc( fin );
    n = 0;
    while ( ch != '\n' ) {
        text[n] = ch;
        n++;
        ch = fgetc( fin );
    }

    p1 = p2 = 1;
    hashPat1 = hashPat2 = 0;
    for ( i = 0; i < m; i++ ) {
        hashPat1 = (hashPat1 * SIGMA + pat[i]) % MOD1;
        hashPat2 = (hashPat2 * SIGMA + pat[i]) % MOD2;
        if ( i > 0 ) {
            p1 = (p1 * SIGMA) % MOD1;
            p2 = (p2 * SIGMA) % MOD2;
        }
    }

    hashText1 = hashText2 = 0;
    for ( i = 0; i < m; i++ ) {
        hashText1 = ((long long)hashText1 * SIGMA + text[i]) % MOD1;
        hashText2 = ((long long)hashText2 * SIGMA + text[i]) % MOD2;
    }

    nrSol = 0;
    if ( hashPat1 == hashText1 && hashPat2 == hashText2 ) {
        sol[nrSol] = 0;
        nrSol++;
    }
    for ( i = m; i < n; i++ ) {
        hashText1 = (hashText1 - ((long long)text[i - m] * p1) % MOD1 + MOD1) % MOD1;
        hashText1 = ((long long)hashText1 * SIGMA + text[i]) % MOD1;
        hashText2 = (hashText2 - ((long long)text[i - m] * p2) % MOD2 + MOD2) % MOD2;
        hashText2 = ((long long)hashText2 * SIGMA + text[i]) % MOD2;
        if ( hashPat1 == hashText1 && hashPat2 == hashText2 ) {
            if ( nrSol < MAX_SOL )
                sol[nrSol] = i - m + 1;
            nrSol++;
        }
    }

    fout = fopen( "strmatch.out", "w" );
    fprintf( fout, "%d\n", nrSol );
    for ( i = 0; i < (nrSol < MAX_SOL ? nrSol : MAX_SOL); i++ )
        fprintf( fout, "%d ", sol[i] );
    fclose( fout );

    return 0;
}