【代码】
KMP模板
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#include<set>
using namespace std;
#define f(i,n) for(int i=1;i<=(n);i++)
#define ll long long
#define INF 1<<30
#define N 100010
int read()
{
int x=0,f=1;char c=getchar();
while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while( isdigit(c)){x=x*10+c-'0';c=getchar();}
return x*f;
}
int n,m;
char a[N],b[N];
int next[N];
void get_next()
{
int j=0,k=-1,l=strlen(a);
next[0]=-1;
while(j<l)
{
if(k==-1||a[j]==a[k])
{
k++;
j++;
if(a[j]!=a[k])next[j]=k;
else next[j]=next[k];
}
else k=next[k];
}
/*for(int i=0;i<j;i++)cout<<next[i]<<" ";
cout<<endl;*/
}
int KMP()
{
if(a[0]==' '||b[0]==' ')return -1;
get_next();
int ans=0,i=0,j=0;
while(b[i]!=' '&&a[j]!=' ')
{
if(b[i]==a[j])
{
i++;
j++;
}
else
{
ans+=j-next[j];
if(next[j]!=-1)j=next[j];
else
{
j=0;
i++;
}
}
}
if(a[j]==' ')return ans;
return -1;
}
int main()
{
scanf("%s",b);
scanf("%s",a);
printf("%d",KMP());
}