Cod sursa(job #150302)

Utilizator thestickTudor A thestick Data 6 martie 2008 20:22:40
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <string.h>
#include <stdio.h>

#define LMAX 2000000

using namespace std;

long n,m;
char t[LMAX],p[LMAX];
long u[LMAX];
long li[1024],tl=0;

void precalc(char *p)
{
int k=-1,x;
u[0]=0;
for(x=1;x<m;x++)
        {
        while(k>0 && p[k+1]!=p[x]) k=u[k];
        if(p[k+1]==p[x])k++;
        u[x]=k;
        }
}


void cit()
{
ifstream f("strmatch.in");
f.getline(p,LMAX);
m=strlen(p);
f.getline(t,LMAX);
n=strlen(t);
}

void brute()
{
int i,x=-1;
for(i=0;i<n;i++)
        {
        while(x>0 && p[x+1]!=t[i]) x=u[x];
        if(p[x+1]==t[i]) x++;
        if(x==m-1)
                {
                //printf("%d ",i-m+1);
                if(tl<1000)
                        {
                        li[tl]=i-m+1;
                        tl++;
                        }
                else
                        {
                        tl++;
                        }
                x=u[x];
                }
        }
}

void tip()
{
FILE *f;
int i;
f=fopen("strmatch.out","w");
fprintf(f,"%d\n",tl);
if(tl)
{
if(tl<1000)
	{
	for(i=0;i<tl;i++)
	fprintf(f,"%d ",li[i]);
	}

if(tl>=1000)
	{
	for(i=0;i<1000;i++)
	fprintf(f,"%d ",li[i]);
	}
fprintf(f,"\n");
}
fclose(f);
}

int main()
{
cit();
precalc(p);
brute();
tip();
return 0;
}