Cod sursa(job #2281875)

Utilizator I_am_not_a_robotMr Domino I_am_not_a_robot Data 12 noiembrie 2018 21:26:36
Problema Potrivirea sirurilor Scor 8
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int N = 2000000 + 5;

string pat, s;
int n, m;
int ps[N];

vector<int>id;

inline void build_ps()
{
    ps[0] = 1;
    int i = 1;
    int cur = 0;
    while (i < m)
    {
        if (pat[i] == pat[cur])
        {
            cur++;
            ps[i] = cur;
            i++;
        }
        else
        {
            if (cur == 0)
            {
                i++;
            }
            else
            {
                cur = ps[cur - 1];
            }
        }
    }
}

inline void kmp()
{
    int i = 0;
    int j = 0;
    while (i < n)
    {
        if (s[i] == pat[j])
        {
            i++;
            j++;
        }
        if (j == m)
        {
            id.push_back (i - m);
            j = ps[j - 1];
        }
        else
        {
            if (i < n && s[i] != pat[j])
            {
                if (j == 0)
                {
                    i++;
                }
                else
                {
                    j = ps[j - 1];
                }
            }
        }
    }
}

int main()
{
    fin >> pat >> s;
    m = pat.size();
    n = s.size();
    build_ps();
    kmp();
    fout << id.size() << "\n";
    if (id.size() > 1000)
    {
        id.resize (1000);
    }
    for (auto &x : id)
    {
        fout << x << " ";
    }
    fout << "\n";
    return 0;
}