Cod sursa(job #2592560)

Utilizator OnofreiTudorOnofrei Tudor OnofreiTudor Data 1 aprilie 2020 21:18:21
Problema Potrivirea sirurilor Scor 40
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <stdio.h>
#include <string.h>

#define PRIM1 100007
#define PRIM2 100021

char N[2000002], M[2000002];
int i, n, m, valori, p[1001];
int putere1, putere2, hash11, hash12, hash21, hash22, val;

int main()
{
    FILE *fp;
    FILE *fw;
    fp = fopen("strmatch.in", "r");
    fscanf(fp, "%s %s", M, N);
    fclose(fp);

    fw = fopen("strmatch.out", "w");

    putere1 = putere2 = 1;
    n = strlen(N);
    m = strlen(M);
    if(m > n){
        fprintf(fw, "%d", 0);
        return 0;
    }
    hash11 = hash12 = 0;
    for(i = 0; i<=m-1; i++){
        hash11 = (hash11 * 73 + M[i]) % PRIM1;
        hash12 = (hash12 * 73 + M[i]) % PRIM2;
        if(i != 0){
            putere1 = (putere1 * 73) % PRIM1;
            putere2 = (putere2 * 73) % PRIM2;
        }
    }
    hash21 = hash22 = 0;
    for(i = 0; i<=m-1; i++){
        hash21 = (hash21 * 73 + N[i]) % PRIM1;
        hash22 = (hash22 * 73 + N[i]) % PRIM2;
    }
    if(hash11 == hash21 && hash12 == hash22){
        valori++;
        p[valori] = 0;
    }
    for(i = m; i<n; i++){
        hash21 = ((hash21 - (N[i-m]*putere1) % PRIM1 + PRIM1) * 73 + N[i]) % PRIM1;
        hash22 = ((hash22 - (N[i-m]*putere2) % PRIM2 + PRIM2) * 73 + N[i]) % PRIM2;
        if(hash11 == hash21 && hash12 == hash22){
            valori++;
            p[valori] = i-m+1;
        }
    }
    if(valori > 1000){
        valori = 1000;
    }
    fprintf(fw, "%d %s", valori, "\n");
    for(i = 1; i<=valori; i++){
        fprintf(fw, "%d ", p[i]);
    }
    fclose(fw);
    return 0;
}