Cod sursa(job #1145231)

Utilizator Claudiu95Vartolomei Alexandru Claudiu Claudiu95 Data 17 martie 2014 23:36:09
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include<fstream>
#include<string.h>
#define maxx 2000005
using namespace std;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
char P[maxx], T[maxx];
int nr, sol[maxx],urm[maxx],m,n;

void prefix(char *P){
	int k=0;
	urm[1]=0;
	for(int x=2;x<=m;++x){
		while(k>0 && P[x]!=P[k+1])
			k=urm[k];
		if(P[x]==P[k+1])
			++k;
		urm[x]=k;
	}
}
void KMP(char *T){
	int x=0;	
	for(int i=1;i<=n;++i){
		while(x>0 && T[i]!=P[x+1])
			x=urm[x];
		if(T[i]==P[x+1])
			++x;
		if(x==m){
			x=urm[x];
			++nr;
			sol[nr]=i-m;
		}
	}
}


int main(){
	f.getline(P,maxx);
	f.getline(T,maxx);
	m=strlen(P);
	n=strlen(T);
	for(int i=m;i>0;--i)
		P[i]=P[i-1]; P[0]=' ';
	for(int i=n;i>0;--i)
		T[i]=T[i-1];T[0]=' ';
	prefix(P);
	KMP(T);
	g<<nr<<"\n";
	nr=min(nr,1000);
	for(int i=1;i<=nr;++i)
		g<<sol[i]<<" ";
	return 0;
}