Cod sursa(job #3341647)

Utilizator Cristian_NegoitaCristian Negoita Cristian_Negoita Data 20 februarie 2026 15:25:51
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
const int DIM = 2e6 + 1;
int n, m, lps[DIM + DIM];
string needle, haystack;
vector<int> positions;

void precalculare()
{
    lps[0] = 0;
    for(int i = 1; i < m; i++)
    {
        int j = lps[i - 1];
        while(j > 0 && haystack[j] != haystack[i])
            j = lps[j - 1];
        j += (haystack[j] == haystack[i]);
        lps[i] = j;
    }
}

int main()
{
    fin >> needle >> haystack;
    n = needle.size();
    haystack = needle + '*' + haystack;
    m = haystack.size();
    precalculare();
    for(int i = n + 1; i < m; i++)
        if(lps[i] == n)
            positions.push_back(i - 2 * n);
    fout << positions.size() << "\n";
    for(int i = 0; i < min(1000, (int)positions.size()); i++)
        fout << positions[i] << " ";

    fin.close();
    fout.close();
    return 0;
}