Cod sursa(job #1360113)

Utilizator mirceadinoMircea Popoveniuc mirceadino Data 25 februarie 2015 11:47:33
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include<cstdio>
#include<string>
#include<cstring>

using namespace std;

#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "strmatch";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif

const int NMAX = 2000000 + 5;
const int BASE1 = 127;
const int BASE2 = 197;
const int MOD1 = (int)(1e6) + 3;
const int MOD2 = 666013;

int N, M;
int pi[NMAX];
char A[NMAX];
char B[NMAX];
int nr_matches;
int matches[1005];

int H1, H2;
int P1, P2;

void add(int i) {
    nr_matches++;
    if(nr_matches <= 1000)
        matches[nr_matches] = i - N;
}

void hashes() {
    int i;

    P1 = P2 = 1;
    H1 = H2 = 0;

    for(i = 1; i <= N; i++) {
        P1 = (P1 * 1LL * BASE1) % MOD1;
        P2 = (P2 * 1LL * BASE2) % MOD2;

        H1 = (H1 * 1LL * BASE1 + A[i]) % MOD1;
        H2 = (H2 * 1LL * BASE2 + A[i]) % MOD2;
    }
}

void rolling() {
    int i, h1, h2;

    h1 = h2 = 0;

    for(i = 1; i < N; i++) {
        h1 = (h1 * 1LL * BASE1 + B[i]) % MOD1;
        h2 = (h2 * 1LL * BASE2 + B[i]) % MOD2;
    }

    for(i = N; i <= M; i++) {
        h1 = (h1 * 1LL * BASE1 + B[i]) % MOD1;
        h1 = ((h1 - P1 * 1LL * B[i - N]) % MOD1 + MOD1) % MOD1;

        h2 = (h2 * 1LL * BASE2 + B[i]) % MOD2;
        h2 = ((h2 - P2 * 1LL * B[i - N]) % MOD2 + MOD2) % MOD2;

        if(h1 == H1 && h2 == H2)
            add(i);
    }
}

int main() {
    int i;

    freopen(inputFile.c_str(), "r", stdin);
    freopen(outputFile.c_str(), "w", stdout);

    scanf("%s", A + 1);
    scanf("%s", B + 1);

    N = strlen(A + 1);
    M = strlen(B + 1);

    hashes();
    rolling();

    printf("%d\n", nr_matches);

    for(i = 1; i <= min(nr_matches, 1000); i++)
        printf("%d ", matches[i]);

    return 0;
}