Cod sursa(job #865309)

Utilizator batistaUPB-Oprea-Cosmin-Dumitru batista Data 26 ianuarie 2013 12:34:42
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <stdio.h>
#include <string.h>

#define N 2000001

#define P 73
#define MOD1 100007
#define MOD2 100021

char A[N], B[N], match[N];
int NA, NB, Nr, hashA1, hashA2, hashB1, hashB2, P1, P2;

int main()
{
    freopen("strmatch.in", "rt", stdin);
    freopen("strmatch.out", "wt", stdout);

    scanf("%s %s", A, B);//A subsir ,B sir
    NA = strlen(A);
    NB = strlen(B);
    if (NA > NB)
    {
        printf("0\n");
        return 0;
    }

    P1 = P2 = 1;
    for (int i = 0; i < NA; i++)
    {
        hashA1 = (hashA1 * P + A[i]) % MOD1;
        hashA2 = (hashA2 * P + A[i]) % MOD2;
        hashB1 = (hashB1 * P + B[i]) % MOD1;
        hashB2 = (hashB2 * P + B[i]) % MOD2;
        if (i != 0)
            P1 = (P1 * P) % MOD1,
            P2 = (P2 * P) % MOD2;
    }
    if (hashB1 == hashA1 && hashB2 == hashA2)
        match[0] = 1, Nr++;

    for (int i = NA; i < NB; i++)
    {
        hashB1 = ((hashB1 - (B[i - NA] * P1)%MOD1 + MOD1) * P + B[i]) % MOD1;
        hashB2 = ((hashB2 - (B[i - NA] * P2)%MOD2 + MOD2) * P + B[i]) % MOD2;

        if (hashB1 == hashA1 && hashB2 == hashA2)
            match[ i - NA + 1 ] = 1, Nr++;
    }
    printf("%d\n", Nr);

    Nr = 0;
    for (int i = 0; i < NB ; i++)
        if (match[i])
            Nr++,
            printf("%d ", i);
    printf("\n");

    return 0;
}