Luogu-P3375 【模板】KMP字符串匹配
题目
测试得分: 100
主要算法 : 字符串KMP
题干:
KMP板子题
代码
#include<stdio.h> #include<stdlib.h> #include<string.h> #define FORa(i,s,e) for(int i=s;i<=e;i++) #define FORs(i,s,e) for(int i=s;i>=e;i--) #define gc pa==pb&&(pb=(pa=buf)+fread(buf,1,100000,stdin),pa==pb)?EOF:*pa++ #define File(name) freopen(name".in","r",stdin);freopen(name".out","w",stdout); using namespace std; static char buf[100000],*pa=buf,*pb=buf; inline int read(); const int MAXN=1000000; char sta[MAXN+1],stb[MAXN+1]; int lena,lenb,next[MAXN+1]; int main() { scanf("%s%s",sta+1,stb+1); lena=strlen(sta+1),lenb=strlen(stb+1); int j=0; FORa(i,2,lenb) { while(j&&stb[i]!=stb[j+1]) j=next[j]; if(stb[i]==stb[j+1]) j++; next[i]=j; } j=0; FORa(i,1,lena) { while(j&&sta[i]!=stb[j+1]) j=next[j]; if(sta[i]==stb[j+1]) j++; if(j==lenb) printf("%d\n",i-lenb+1),j=next[j]; } FORa(i,1,lenb) printf("%d ",next[i]); return 0; } inline int read() { register int x(0);register int f(1);register c(gc); while(c<'0'||c>'9') f=c=='-'?-1:1,c=gc; while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=gc; return x*f; }