http://acm.hdu.edu.cn/showproblem.php?pid=1711
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
int n,m;
int next[10011];
int a[1000111];
int b[10011];
void getnext()
{
int j,k;
j=0;
k=-1;
next[0]=-1;
while(j<m)
{
if(k==-1 || b[j]==b[k]) next[++j]=++k;
else k=next[k];
}
}
int KMP()
{
int i,j;
j=0;
for(i=0;i<n;)
{
if(a[i]==b[j])
{
if(j==m-1) return i-(m-1)+1;
i++;j++;
}
else
{
j=next[j];
if(j==-1) {i++;j=0;}
}
}
return -1;
}
int main()
{
int T;
int i;
int ans;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(i=0;i<n;i++) scanf("%d",&a[i]);
for(i=0;i<m;i++) scanf("%d",&b[i]);
if(n<m) {printf("-1\n");continue;}
getnext();
ans=KMP();
printf("%d\n",ans);
}
return 0;
}
#include<bits/stdc++.h>//https://www.bnuoj.com/v3/contest_show.php?cid=6865#problem/C
using namespace std;
const int N=5e6+10;
char a[N],b[N],ans[N];
int next[N],pos[N];
void getnext()
{
int i=0,j=-1;
next[0]=-1;
while(b[i]!='\0')
{
if(j==-1||b[i]==b[j]) next[++i]=++j;
else j=next[j];
}
}
void kmp()
{
getnext();
int i=0,j=0,cnt=0,x=strlen(b);
while(a[i]!='\0')
{
ans[cnt]=a[i++];
while(!(j==-1||ans[cnt]==b[j]))
j=next[j];
j++;cnt++;
pos[cnt]=j;
if(j==x) cnt-=x,j=pos[cnt];
}
ans[cnt]='\0';
}
int main()
{
int n,m,x,y,t;
while(~scanf("%s%s",b,a))
{
kmp();
printf("%s\n",ans);
}
return 0;
}
#include<bits/stdc++.h>//http://acm.hdu.edu.cn/showproblem.php?pid=1711
using namespace std;
const int N=5e6+10;
char a[N],b[N],ans[N];
int next[N];
void getnext()
{
int i=0,j=-1;
next[0]=-1;
while(b[i]!='\0')
{
if(j==-1||b[i]==b[j]) next[++i]=++j;
else j=next[j];
}
}
int kmp()
{
getnext();
int i=0,j=0;
while(a[i]!='\0')
{
if(a[i]==b[j])
{
if(b[j+1]=='\0') return i-j+1;
i++,j++;
}
else
{
j=next[j];
if(j==-1) i++,j=0;
}
}
return -1;
}
int main()
{
int n,m,x,y,t;
while(~scanf("%s%s",a,b))
{
printf("%d\n",kmp());
}
return 0;
}