Cod sursa(job #1129271)

Utilizator vasandANDREI POP vasand Data 27 februarie 2014 21:05:25
Problema Potrivirea sirurilor Scor 14
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
# include <iostream>
# include <fstream>
# include <string.h>
# define nmax 2000010
using namespace std;

ifstream f("strmatch.in");

char a[nmax], b[nmax];
int na, nb, L[nmax];

void pref()
{
    int k, p;
    L[0]=0;
    k=0;

    for(p=1; p<na; p++)
    {
        k=L[p-1];
        while(k>0 && a[k]!=a[p])
            k=L[k-1];
        if(a[k]==a[p])
            k+=1;
        L[p]=k;
    }
}


void kmp()
{
    int p,k=0,nr=0;

    fstream g("strmatch.out", ios::out);
    g<<'\n';
    for(p=0; p<nb; p++)
    {
        while(k>0 && a[k]!=b[p])
            k=L[k-1];
        if(b[p]==a[k])
            k+=1;
        if(k==na)
        {
            nr+=1;
            g<<p-na+1<<" ";
            k=L[k-1];
        }
    }

    g.close();
    g.open("strmatch.out", ios::in | ios::out);
    g<<nr;
    g.close();
}

int main()
{
    f.getline(a,nmax);
    f.getline(b,nmax);
    na=strlen(a);
    nb=strlen(b);

    pref();
    kmp();

    return 0;
}