KMP模板
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5 + 7;
int n,m;
int nxt[N];
char s[N];
char p[N];
void get_next()
{
int i = 0,j = -1;
nxt[0] = -1;
while (i < m){
if (j == -1 || p[i] == p[j]){
i++;
j++;
nxt[i] = j;
}else{
j = nxt[j];
}
}
}
int KMP()
{
int i = 0,j = 0;
while (i < n){
if (j == -1 || s[i] == p[j]){
i++;
j++;
}else{
j = nxt[j];
}
if (j == m) {
return i - j + 1;
}
}
return -1;
}
int main()
{
scanf("%s",s);
scanf("%s",p);
n = strlen(s);
m = strlen(p);
get_next();
printf("KMP = %d\n",KMP());
return 0;
}