题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6153
2017CCPC网络赛题
flag:KMP
*先reserve 字符串S1、S2,将问题,变为:求S2的所有前缀在S1中出现的次数乘以其长度之和;
*在得到串S2的Next数组的同时,我们预处理得到sum[i](定义为:S2的0—i-1的子串的所有前后缀的长度之和),
sum[i]=i+sum[Next[i]];
*我们在KMP匹配的过程中:遍历S1的每个字符,获取S1当中以S1[i]结尾的S2当中的最长前缀j;ans+=sum[j];
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string.h>
using namespace std;
const int Size=1e6+100;
const int Mod=1e9+7;
char S1[Size],S2[Size];
int sum[Size];//记录子串1—i的所有前后缀子串的长度和
int Next[Size];
void getNext(){
int j=0;
int str=strlen(S2);
Next[0]=-1;Next[1]=0;
sum[0]=0;sum[1]=1;
for(int i=2;i<=str;++i){
while(j!=-1&&S2[j]!=S2[i-1])j=Next[j];
Next[i]=++j;
sum[i]=(i+sum[j])%Mod;
}
}
int KMP(){
int str1=strlen(S1);
int str2=strlen(S2);
int j=0,ans=0;
for(int i=0;i<str1;++i){
while(j==str2||(j!=-1&&S1[i]!=S2[j]))j=Next[j];
++j;
ans=(ans+sum[j])%Mod;
}
return ans;
}
int main(){
int T;scanf("%d",&T);
while(T--){
scanf("%s",S1);
scanf("%s",S2);
reverse(S1,S1+strlen(S1));
reverse(S2,S2+strlen(S2));
getNext();
printf("%d\n",KMP());
}
return 0;
}