Cod sursa(job #3379470)

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

using namespace std;

static inline uint64_t rotl64(uint64_t x, int r) {
    r &= 63;
    if (r == 0) return x;
    return (x << r) | (x >> (64 - r));
}

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;
    }

    // Generam o cheie aleatorie pe 64 de biti pentru fiecare caracter ASCII posibil
    uint64_t Z[256] = {0};
    mt19937_64 rng(20261130ULL);
    for (int c = 0; c < 256; ++c) {
        Z[c] = rng();
    }

    // Calculam hash-ul pentru A:
    // A[0] va fi rotit de (m - 1) ori pana ajunge la acelasi "offset" cu ultimul element
    uint64_t hashA = 0;
    for (int i = 0; i < m; ++i) {
        hashA ^= rotl64(Z[static_cast<unsigned char>(A[i])], m - 1 - i);
    }

    uint64_t hashB = 0;
    vector<int> positions;
    positions.reserve(1000);
    int total_matches = 0;

    for (int i = 0; i < n; ++i) {
        if (i >= m) {
            hashB = rotl64(hashB, 1);
            hashB ^= rotl64(Z[static_cast<unsigned char>(B[i - m])], m);
        }
        hashB ^= Z[static_cast<unsigned char>(B[i])];

        if (i >= m - 1 && hashB == hashA) {
            int start_pos = i - m + 1;
            // Verificare directa pentru a elimina complet riscul coliziunilor
            if (B.compare(start_pos, m, A) == 0) {
                ++total_matches;
                if (static_cast<int>(positions.size()) < 1000) {
                    positions.push_back(start_pos);
                }
            }
        }
    }

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

    return 0;
}