Cod sursa(job #3357958)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:15:47
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <string>
#include <vector>

using namespace std;

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

    string A, B;
    getline(fin, A);
    getline(fin, B);

    if (!A.empty() && A.back() == '\r') A.pop_back();
    if (!B.empty() && B.back() == '\r') B.pop_back();

    int na = (int)A.length();
    int nb = (int)B.length();

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

    vector<int> pi(na, 0);
    for (int i = 1; i < na; ++i) {
        int j = pi[i - 1];
        while (j > 0 && A[i] != A[j]) {
            j = pi[j - 1];
        }
        if (A[i] == A[j]) {
            j++;
        }
        pi[i] = j;
    }

    vector<int> matches;
    int j = 0;
    for (int i = 0; i < nb; ++i) {
        while (j > 0 && B[i] != A[j]) {
            j = pi[j - 1];
        }
        if (B[i] == A[j]) {
            j++;
        }
        if (j == na) {
            matches.push_back(i - na + 1);
            j = pi[j - 1];
        }
    }

    fout << matches.size() << "\n";
    int cnt = (int)matches.size();
    if (cnt > 1000) cnt = 1000;
    for (int i = 0; i < cnt; ++i) {
        fout << matches[i] << " ";
    }

    return 0;
}