Cod sursa(job #2768216)

Utilizator ParutixLungeanu Razvan Parutix Data 9 august 2021 20:37:41
Problema Potrivirea sirurilor Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

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

int cnt, ans[10005], k;
char pattern[2000005], txt[2000005];

void preProcesare(char pat[], int M, int lps[])
{
    int len = 0;
    lps[0] = 0;
    int i = 1;

    while (i < M)
    {
        if (pat[i] == pat[len])
        {
            len++;
            lps[i] = len;
            i++;
        }
        else
        {

            if (len != 0)
            {
                len = lps[len - 1];
            }
            else
            {
                lps[i] = 0;
                i++;
            }
        }
    }
}

void KMPSearch(char pat[], char txt[])
{
    int M = strlen(pat);
    int N = strlen(txt);

    int lps[M];

    preProcesare(pat, M, lps);

    int i = 0;
    int j = 0;
    while (i < N)
{
        if (pat[j] == txt[i])
        {
            j++;
            i++;
        }

        if (j == M)
        {
            ans[cnt++] = i - j;
            j = lps[j - 1];
        }

        else if (i < N && pat[j] != txt[i])
        {
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
}

int main()
{
    fin.getline(pattern, sizeof(pattern));
    fin.getline(txt, sizeof(txt));

    KMPSearch(pattern, txt);

    fout << cnt << "\n";
    int minim = min(cnt, 1000);
    for(int i = 0; i < minim; ++i)
        fout << ans[i] << " ";

    return 0;
}