Cod sursa(job #1144661)

Utilizator DanutsDanut Rusu Danuts Data 17 martie 2014 13:46:29
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include<fstream>
#include<string.h>
#include<algorithm>
#include<iostream>
#define maxn 2000010
using namespace std;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
char P[maxn],T[maxn];
int urm[maxn],n,m,sol[maxn],nrs;

void Urmator(char P[maxn]){
	int k=0;
	urm[1]=0;
	for(int i=2;i<=m;i++){
		while(k>0 && P[k+1]!=P[i])
			k=urm[k];
		if(P[k+1]==P[i])
			k++;
		urm[i]=k;
	}
}
int main (){
	f.getline(P,maxn);
	f.getline(T,maxn);
	m=strlen(P);
	n=strlen(T);
	//cout<<m<<" "<<n;
	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]=' ';
	Urmator(P);
	int x=0;
	for(int i=1;i<=n;i++){
		while ( x>0 && P[x+1]!=T[i] )
			x=urm[x];
		
		if(P[x+1]==T[i])
			x++;
		if(x==m){
			nrs++;
			sol[nrs]=i-m;
			x=urm[x];
		}
	}
	g<<nrs<<endl;
	for(int i=1;i<=min(1000,nrs);i++)
		g<<sol[i]<<" ";
	return 0;
}