Cod sursa(job #1328175)

Utilizator theprdvtheprdv theprdv Data 28 ianuarie 2015 05:57:04
Problema Potrivirea sirurilor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
// Rabin Karp (2 bases)
#include <fstream>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;

fstream fin("strmatch.in", ios::in);
fstream fout("strmatch.out", ios::out);

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

char A[MAX], B[MAX];
int NA, NB;
int hashA1, hashA2, P1, P2, sol[1001];

int main()
{
    int P1=1, P2=1;
    fin.getline(A, MAX);    NA=strlen(A);
    fin.getline(B, MAX);    NB=strlen(B);

    P1 = P2 = 1;
    hashA1 = hashA2 = 0;
    for (int i = 0; i < NA; i++)
    {
        hashA1 = (hashA1 * P + A[i]) % MOD1;
        hashA2 = (hashA2 * P + A[i]) % MOD2;

        if (i != 0)
            P1 = (P1 * P) % MOD1,
            P2 = (P2 * P) % MOD2;
    }

    if (NA > NB)
    {
        printf("0\n");
        return 0;
    }

    int hash1 = 0, hash2 = 0;
    for (int i = 0; i < NA; i++)
        hash1 = (hash1 * P + B[i]) % MOD1,
        hash2 = (hash2 * P + B[i]) % MOD2;

    int Nr = 0;
    if (hash1 == hashA1 && hash2 == hashA2)
        sol[++sol[0]]=1;

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

        if (hash1 == hashA1 && hash2 == hashA2){
            sol[0]++;
            if(sol[0]<=1000) sol[sol[0]]=i;
        }
    }
    fout<<sol[0]<<"\n";
    for(int i=1; i<=min(1000, sol[0]); i++)
        fout<<sol[i]<<" ";

    fin.close();
    fout.close();
    return 0;
}