Cod sursa(job #3202881)

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

using namespace std;

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

char a[MAXSZ], b[MAXSZ];
int lps[MAXSZ] = {0};

int main() {
    fin.getline(a, MAXSZ);
    fin.getline(b, MAXSZ);

    int q = 0;
    int n = (int) strlen(a);
    int m = (int) strlen(b);

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

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

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