Cod sursa(job #2460557)

Utilizator deiubejanAndrei Bejan deiubejan Data 23 septembrie 2019 21:51:10
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>
using namespace std;

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

#define cin fin
#define cout fout
/*
*/
const int NMAX=3e6;
int N, M;
char s[NMAX], pat[NMAX];
vector<int>rez;

void read()
{
    cin>>pat>>s;
    N=strlen(s);
    M=strlen(pat);
}

void computeLPSarray(char pat[NMAX], int M, int lps[NMAX])
{
    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++;
            }
        }
    }
    /*
    for(int i=0; i<M; i++)
        cout<<lps[i]<<" ";
    cout<<"\n";
    */
}


void KMPsearch(char txt[NMAX], char pat[NMAX])
{
    int lps[M];
    ///length of the previous longest prefix suffix
    computeLPSarray(pat, M, lps);
    int i=0;
    int j=0;
    while(i<N)
    {
        if(pat[j]==txt[i])
        {
            i++;
            j++;
        }
        if(j==M)
        {
            rez.push_back(i-M);
            j=lps[j-1];
        }
        else
        if(i<N && pat[j]!=txt[i])
        {
            if(j!=0)
                j=lps[j-1];
            else
                i++;
        }
    }
}

void print()
{
    int siz=rez.size();
    cout<<siz<<"\n";
    siz=min(siz,1000);
    for(int i=0; i<siz; i++)
        cout<<rez[i]<<" ";
}

int main()
{
    read();
    KMPsearch(s,pat);
    print();


    return 0;
}