Cod sursa(job #1218218)

Utilizator RazvanR104Razvan-Andrei Ciocoiu RazvanR104 Data 10 august 2014 00:12:28
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <iostream>
#include <iomanip>
#include <fstream>

#include <algorithm>
#include <bitset>
#include <deque>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>

#if __cplusplus > 199711L
#include <unordered_map>
#include <unordered_set>
#endif

#include <cstdio>
#include <ctime>
#include <cmath>
#include <cstring>
#include <cstdlib>

using namespace std;

typedef long long int64;

ifstream in("strmatch.in");
ofstream out("strmatch.out");

const int LMAX = 2000010, MOD1 = 100007, MOD2 = 100021, M = 73;

int matches;
int64 hashA1, hashA2, hashB1, hashB2, M1 = 1, M2 = 1;
char A[LMAX], B[LMAX];
bool match[LMAX];

int main() {
    int i;

    in.getline(A, LMAX);
    in.getline(B, LMAX);

    for(i = 0; A[i]; ++i) {
        hashA1 = (hashA1 * M + A[i]) % MOD1;
        hashA2 = (hashA2 * M + A[i]) % MOD2;

        if (i > 0) {
            M1 = (M * M1) % MOD1;
            M2 = (M * M2) % MOD2;
        }
    }

    for(i = 0; A[i]; ++i) {
        if (B[i] == 0) {
            out << "0\n";
            in.close(), out.close();
            return 0;
        }

        hashB1 = (hashB1 * M + B[i]) % MOD1;
        hashB2 = (hashB2 * M + B[i]) % MOD2;
    }

    if (hashA1 == hashB1 && hashA2 == hashB2) {
        match[0] = true;
        ++matches;
    }

    int len_A = i;
    for ( ; B[i] && matches < 1000; ++i) {
        hashB1 = ((hashB1 - B[i - len_A] * M1 % MOD1 + MOD1) * M + B[i]) % MOD1;
        hashB2 = ((hashB2 - B[i - len_A] * M2 % MOD2 + MOD2) * M + B[i]) % MOD2;

        if (hashA1 == hashB1 && hashA2 == hashB2) {
            match[i - len_A + 1] = true;
            ++matches;
        }
    }

    out << matches << '\n';
    for (i = 0; B[i] && matches; ++i)
        if (match[i]) {
            out << i << ' ';
            --matches;
        }
    out << '\n';

    in.close(), out.close();
    return 0;
}