Cod sursa(job #3379472)

Utilizator pitradaPit-Rada Ionel-Vasile pitrada Data 30 noiembrie 2026 18:46:34
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <cstdint>
#include <fstream>
#include <random>
#include <string>
#include <vector>

using namespace std;

int main() {
    ifstream fin("strmatch.in");
    ofstream fout("strmatch.out");

    string A, B;
    if (!getline(fin, A)) return 0;
    while (!A.empty() && (A.back() == '\r' || A.back() == '\n')) A.pop_back();

    if (!getline(fin, B)) B.clear();
    while (!B.empty() && (B.back() == '\r' || B.back() == '\n')) B.pop_back();

    int m = static_cast<int>(A.size());
    int n = static_cast<int>(B.size());

    if (m == 0 || m > n) {
        fout << 0 << "\n\n";
        return 0;
    }

    // Doua tabele Zobrist independente pe 64 de biti + doua baze impare aleatorii
    uint64_t Z1[256], Z2[256];
    mt19937_64 rng(0x9E3779B97F4A7C15ULL);
    for (int c = 0; c < 256; ++c) {
        Z1[c] = rng();
        Z2[c] = rng();
    }
    uint64_t P1 = rng() | 1ULL;
    uint64_t P2 = rng() | 1ULL;

    uint64_t hashA1 = 0, hashA2 = 0;
    uint64_t powP1 = 1, powP2 = 1;
    for (int i = 0; i < m; ++i) {
        unsigned char c = static_cast<unsigned char>(A[i]);
        hashA1 = hashA1 * P1 + Z1[c];
        hashA2 = hashA2 * P2 + Z2[c];
        powP1 *= P1;
        powP2 *= P2;
    }

    uint64_t hashB1 = 0, hashB2 = 0;
    vector<int> positions;
    positions.reserve(1000);
    int total_matches = 0;

    for (int i = 0; i < n; ++i) {
        unsigned char c_in = static_cast<unsigned char>(B[i]);
        hashB1 = hashB1 * P1 + Z1[c_in];
        hashB2 = hashB2 * P2 + Z2[c_in];

        if (i >= m) {
            unsigned char c_out = static_cast<unsigned char>(B[i - m]);
            hashB1 -= Z1[c_out] * powP1;
            hashB2 -= Z2[c_out] * powP2;
        }

        if (i >= m - 1 && hashB1 == hashA1 && hashB2 == hashA2) {
            ++total_matches;
            if (static_cast<int>(positions.size()) < 1000) {
                positions.push_back(i - m + 1);
            }
        }
    }

    fout << total_matches << "\n";
    for (size_t idx = 0; idx < positions.size(); ++idx) {
        if (idx > 0) fout << ' ';
        fout << positions[idx];
    }
    fout << "\n";

    return 0;
}