Cod sursa(job #3337497)

Utilizator sankeeeeAndrei Lascu sankeeee Data 28 ianuarie 2026 09:42:03
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <fstream>
using namespace std;

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

static void buildLPS(const string &p, vector<int> &lps) {
    int m = (int)p.size();
    lps.assign(m, 0);
    int len = 0;
    for (int i = 1; i < m; ) {
        if (p[i] == p[len]) {
            lps[i++] = ++len;
        } else if (len != 0) {
            len = lps[len - 1];
        } else {
            lps[i++] = 0;
        }
    }
}

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

    string pat, txt;
    fin >> pat >> txt;

    int m = (int)pat.size();
    int n = (int)txt.size();

    vector<int> lps;
    buildLPS(pat, lps);

    long long total = 0;
    vector<int> pos;
    pos.reserve(1000);

    int i = 0, j = 0;
    while (i < n) {
        if (txt[i] == pat[j]) {
            i++; j++;
            if (j == m) {
                total++;
                if ((int)pos.size() < 1000) pos.push_back(i - j);
                j = lps[j - 1];
            }
        } else {
            if (j != 0) j = lps[j - 1];
            else i++;
        }
    }

    fout << total << "\n";
    for (int k = 0; k < (int)pos.size(); k++) {
        fout << pos[k] << (k + 1 == (int)pos.size() ? '\n' : ' ');
    }
    return 0;
}