Cod sursa(job #977825)

Utilizator crisbodnarCristian Bodnar crisbodnar Data 26 iulie 2013 19:09:57
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int N = 2000010;

string T, P;
int n, m, sol, urm[N];
vector <int> poz;

void Prefix()
{
    int k = -1;
    for(int q=1; q<m; q++)
    {
        while(k > 0 && P[k+1] != P[q])
            k = urm[k];
        if(P[k+1] == P[q]) k++;
        urm[q] = k;
    }
}

int main()
{
    fin>>P>>T;
    m = P.length(), n = T.length();
    Prefix(); int x = -1;
    for(int i=0; i<n; i++)
    {
        while(x > 0 && P[x+1] != T[i])
            x = urm[x];
        if(P[x+1] == T[i]) x++;
        if(x == m-1)
        {
            sol++;
            x = urm[x];
            poz.push_back(i-m+1);
        }
    }
    fout<<sol<<'\n';
    for(unsigned i=0; i<poz.size() && i < 1000; i++)
        fout<<poz[i]<<' ';
    return 0;
}