Cod sursa(job #3333262)

Utilizator abetAlbert Voiculescu abet Data 12 ianuarie 2026 17:28:44
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>
using namespace std;

ifstream in("strmatch.in");
ofstream out("strmatch.out");
vector<int> searchPattern(const string &text, const string &pattern) {
    int n = text.size();
    int m = pattern.size();
    vector<int> result;

    if (m == 0 || m > n) return result;

    // Randomized base (good practice for very long inputs)
    static const uint64_t BASE = 1315423911ULL;

    uint64_t patHash = 0;
    uint64_t txtHash = 0;
    uint64_t power = 1;   // BASE^(m-1)

    // Build initial hashes
    for (int i = 0; i < m; i++) {
        patHash = patHash * BASE + (unsigned char)pattern[i];
        txtHash = txtHash * BASE + (unsigned char)text[i];
        if (i < m - 1)
            power *= BASE;
    }

    // Sliding window
    for (int i = 0; i <= n - m; i++) {
        if (txtHash == patHash) {
            // Optional verification (recommended for 100% safety)
            if (text.compare(i, m, pattern) == 0)
                result.push_back(i);
        }

        // Slide window
        if (i + m < n) {
            txtHash -= power * (unsigned char)text[i];
            txtHash = txtHash * BASE + (unsigned char)text[i + m];
        }
    }

    return result;
}

int main() {
    ios::sync_with_stdio(false);
    in.tie(nullptr);

    string text, pattern;

    // Example input
    in >> pattern >> text;

    vector<int> matches = searchPattern(text, pattern);
    out<<matches.size()<<'\n';
    for (int idx : matches)
        out << idx << " ";

    out << "\n";
    return 0;
}