扩展kmp板子

using namespace std;
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 1000010
int n,m;
char a[N],b[N];
int nxt[N],ex[N];
int main(){
	scanf("%s%s",a,b);
	n=strlen(a),m=strlen(b);
	nxt[0]=n;
	nxt[1]=0;
	while (1+nxt[1]<n && b[nxt[1]]==b[1+nxt[1]])
		nxt[1]++;
	int pos=1,mr=1+nxt[1];
	for (int i=2;i<m;++i){
		if (i<mr)
			nxt[i]=min(i+nxt[i-pos],mr)-i;
		else
			nxt[i]=0;
		while (i+nxt[i]<m && b[nxt[i]]==b[i+nxt[i]])
			nxt[i]++;
		if (i+nxt[i]>mr){
			mr=i+nxt[i];
			pos=i;
		}
	}
	pos=-1,mr=0;
	for (int i=0;i<n;++i){
		if (i<mr)
			ex[i]=min(i+nxt[i-pos],mr)-i;
		else
			ex[i]=0;
		while (ex[i]<m && i+ex[i]<n && b[ex[i]]==a[i+ex[i]])
			ex[i]++;
		if (i+ex[i]>mr){
			mr=i+ex[i];
			pos=i;
		}
	}
	for (int i=0;i<n;++i)
		printf("%d ",ex[i]);
	return 0;
}
posted @ 2019-04-28 18:56  jz_597  阅读(94)  评论(0编辑  收藏  举报