Cod sursa(job #2274736)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 2 noiembrie 2018 13:47:03
Problema Potrivirea sirurilor Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int N=2000000+5;

string pat;
string s;
int m;
int n;

int PS[N];

inline void buildPS()
{
    PS[0]=0;
    int i=1;
    int len=0;
    while(i<m)
    {
        if(pat[i]==pat[len])
        {
            len++;
            PS[i]=len;
            i++;
        }
        else
        {
            if(len)
            {
                len=PS[len-1];
            }
            else
            {
                PS[i]=0;
                i++;
            }
        }
    }
}

vector<int>ans;

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

int main()
{
    fin>>pat>>s;
    m=pat.size();
    n=s.size();
    buildPS();
    goKMP();
    fout<<ans.size()<<"\n";
    int sz=min((int)ans.size(),1000);
    for(int i=0;i<sz;i++)
    {
        fout<<ans[i]<<" ";
    }
    fout<<"\n";
    return 0;
}