Cod sursa(job #2976770)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 9 februarie 2023 23:05:19
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 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 + 1], b[MAXSZ + 1];

int main() {
    fin.getline(a, MAXSZ);
    fin.getline(b, MAXSZ);
    n = (int) strlen(a);
    m = (int) strlen(b);
    for (int i = n; i > 0; i--)
        a[i] = a[i - 1];
    a[0] = ' ';
    for (int i = m; i > 0; i--)
        b[i] = b[i - 1];
    b[0] = ' ';

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

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

    fout << matches.size() << '\n';
    for (auto& match: matches)
        fout << match << ' ';
    return 0;
}