Cod sursa(job #3148624)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 2 septembrie 2023 22:13:15
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <string>
#include <vector>

using namespace std;

ifstream f("strmatch.in");
ofstream g("strmatch.out");

string A, B;

static inline void read()
{
    f.tie(nullptr);

    A = B = "";
    f >> A >> B;

    return;
}

static inline int my_min(const int &a, const int &b)
{
    return ((a < b) ? a : b);
}

static inline vector<int> get_matching(const string &a, const string &b)
{
    string S = a + "#" + b;
    int n = (int)S.size();

    vector<int> max_pref;
    for (int i = 0; i < n; ++i)
        max_pref.push_back(0);

    max_pref[0] = n;

    int l = 0, r = -1;

    for (int i = 1; i < n; ++i)
    {
        if (l <= i && i <= r)
            max_pref[i] = my_min(max_pref[i - l], (r - i + 1));

        while (i + max_pref[i] < n && S[i + max_pref[i]] == S[max_pref[i]])
            ++max_pref[i];

        if ((i + max_pref[i] - 1) >= r)
            l = i, r = (i + max_pref[i] - 1);
    }

    vector<int> ans = {};

    int _need = (int)a.size();

    for (int i = _need + 1; i < n; ++i)
        if (max_pref[i] == _need)
            ans.push_back(i - (_need + 1));

    return ans;
}

int main()
{
    read();

    vector<int> ans = get_matching(A, B);

    int m = 0;
    g << (m = (int)ans.size()) << '\n';

    m = my_min(m, (int)(1e3));
    for (int i = 0; i < m; ++i)
    {
        g << ans[i];
        if (i == (m - 1))
            g << '\n';
        else
            g << ' ';
    }

    return 0;
}