Cod sursa(job #3280662)

Utilizator Costy2345Costi Dimian Costy2345 Data 27 februarie 2025 01:34:11
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
vector<int> preindex(string& t)
{
    int n = t.size();
    int k = 0;
    vector<int> pi(n, 0);
    for(int i = 1; i < n; i++)
    {
        while(k > 0 && t[k] != t[i])
        {
            k = pi[k - 1];
        }
        if(t[k] == t[i])
        {
            k++;
        }
        pi[i] = k;
    }
    return pi;
}
int main()
{
    string a, b;
    fin >> a >> b;
    vector<int> pi = preindex(a);
    vector<int> matches;
    int q = 0;
    for(int i = 0; i < b.size(); i++)
    {
        while(q > 0 && a[q] != b[i])
        {
            q = pi[q - 1];
        }
        if(a[q] == b[i])
        {
            q++;
        }
        if(q == a.size())
        {
            matches.push_back(i - a.size() + 1);
            q = pi[q - 1];
        }
    }
    fout << matches.size() << endl;
    for(int i = 0; i < matches.size() && i < 1000; i++)
    {
        fout << matches[i] << " ";
    }
    return 0;
}