Cod sursa(job #3321233)

Utilizator andreiaramaArama Andrei Robert andreiarama Data 8 noiembrie 2025 17:43:53
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <string>
#include <vector>
using namespace std;

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

string a, b;
vector<int> prefix;  

void build_prefix() {
    int n = (int)a.size();
    prefix.assign(n, 0);
    int k = 0;
    for (int i = 1; i < n; i++) {
        while (k > 0 && a[k] != a[i])
            k = prefix[k - 1];
        if (a[k] == a[i])
            k++;
        prefix[i] = k;
    }
}

int main() {
    cin >> a >> b;
    build_prefix();

    vector<int> matches;
    int k = 0; 
    for (int i = 0; i < (int)b.size(); i++) {
        while (k > 0 && a[k] != b[i])
            k = prefix[k - 1];
        if (a[k] == b[i])
            k++;
        if (k == (int)a.size()) {
            matches.push_back(i - (int)a.size() + 1); 
            k = prefix[k - 1];
        }
    }

    // Output number of matches and first 1000 matches
    int total_matches = (int)matches.size();
    cout << total_matches << '\n';
    for (int i = 0; i < total_matches && i < 1000; i++) {
        cout << matches[i] << (i == min(total_matches, 1000) - 1 ? '\n' : ' ');
    }

    return 0;
}