Cod sursa(job #3203058)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 13 februarie 2024 08:56:46
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>
#define MAXSZ 2000005

using namespace std;

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

int n, m, lps[MAXSZ];
char a[MAXSZ], b[MAXSZ];

int main() {
    fin.getline(a, MAXSZ);
    fin.getline(b, MAXSZ);
    n = (int) strlen(a);
    m = (int) strlen(b);

    int idx = 0;
    for (int i = 2; i <= n; i++) {
        while (idx && a[i - 1] != a[idx])
            idx = lps[idx];
        if (a[i - 1] == a[idx])
            idx++;
        lps[i] = idx;
    }

    idx = 0;
    vector<int> matches;
    for (int i = 1; i <= m; i++) {
        while (idx && a[idx] != b[i - 1])
            idx = lps[idx];
        if (a[idx] == b[i - 1])
            idx++;
        if (idx == n) {
            matches.push_back(i - n);
            idx = lps[idx];
        }
    }

    fout << matches.size() << '\n';
    for (int i = 0; i < min((int) matches.size(), 1000); i++)
        fout << matches[i] << ' ';
    return 0;
}