Cod sursa(job #3333335)

Utilizator Calin2009Gae Mihai Calin Calin2009 Data 13 ianuarie 2026 10:19:31
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
using namespace std;

ifstream input("strmatch.in");
ofstream output("strmatch.out");

const int LIM = 2000010;

string pattern, source;
int lps[LIM], positions[LIM];
int lenPattern, lenSource, totalMatches;

void buildLPS() {
    int idx = 1, len = 0;
    while (idx < lenPattern) {
        if (pattern[idx] == pattern[len]) {
            lps[idx++] = ++len;
        } else {
            if (len)
                len = lps[len - 1];
            else
                lps[idx++] = 0;
        }
    }
}

void findPattern() {
    int i = 0, j = 0;
    while (i < lenSource) {
        if (source[i] == pattern[j]) {
            i++; j++;
            if (j == lenPattern) {
                positions[++totalMatches] = i - j;
                j = lps[j - 1];
            }
        } else {
            if (j)
                j = lps[j - 1];
            else
                i++;
        }
    }

    output << totalMatches << "\n";
    if (totalMatches > 1000) totalMatches = 1000;
    for (int k = 1; k <= totalMatches; k++)
        output << positions[k] << " ";
}

int main() {
    input >> pattern;
    input >> source;

    lenPattern = pattern.size();
    lenSource = source.size();

    buildLPS();
    findPattern();

    return 0;
}