Problem Description
Today is the birthday of SF,so VS gives two strings S1,S2 to SF as a present,which have a big secret.SF is interested in this secret and ask VS how to get it.There are the things that VS tell:
Suffix(S2,i) = S2[i…len].Ni is the times that Suffix(S2,i) occurs in S1 and Li is the length of Suffix(S2,i).Then the secret is the sum of the product of Ni and Li.
Now SF wants you to help him find the secret.The answer may be very large, so the answer should mod 1000000007.
Input
Input contains multiple cases.
The first line contains an integer T,the number of cases.Then following T cases.
Each test case contains two lines.The first line contains a string S1.The second line contains a string S2.
1<=T<=10.1<=|S1|,|S2|<=1e6.S1 and S2 only consist of lowercase ,uppercase letter.
Output
For each test case,output a single line containing a integer,the answer of test case.
The answer may be very large, so the answer should mod 1e9+7.
题意就是对于B串的每一个后缀,找出在A串中出现了多少次,每一个后缀对答案的贡献是出现次数乘上当前后缀的长度。
这个题的关键是把AB串一起倒置,这样麻烦的后缀就变成了前缀,很巧妙的办法…然后就是扩展kmp的模板套一套,对于A串的ex数组,每一个不为0的值就对答案贡献了1+2+3+…+ex[i],也就是等差数列求和,这个可以自己写一写看一下。
#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <set>
#include <stack>
using namespace std;
#define ll long long
#define maxn 1000005
#define angel 0x3f3f3f3f
#define eps 1e-9
#define my_angel main
const ll mod=1e9+7;
int len1,len2;
int ext[maxn],ex[maxn];//next数组
char str1[maxn],str2[maxn],str3[maxn];
void GETNEXT(char *str)
{
int i=0,j,po,len=strlen(str);
ext[0]=len;
while(str[i]==str[i+1]&&i+1<len)
i++;
ext[1]=i;
po=1;
for(i=2; i<len; i++)
{
if(ext[i-po]+i<ext[po]+po)
ext[i]=ext[i-po];
else
{
j=ext[po]+po-i;
if(j<0)j=0;
while(i+j<len&&str[j]==str[j+i])
j++;
ext[i]=j;
po=i;
}
}
}
void EXKMP(char *s1,char *s2)
{
int i=0,j,po,len=strlen(s1),l2=strlen(s2);
GETNEXT(s2);
while(s1[i]==s2[i]&&i<l2&&i<len)
i++;
ex[0]=i;
po=0;
for(i=1; i<len; i++)
{
if(ext[i-po]+i<ex[po]+po)
ex[i]=ext[i-po];
else
{
j=ex[po]+po-i;
if(j<0)j=0;
while(i+j<len&&j<l2&&s1[j+i]==s2[j])
j++;
ex[i]=j;
po=i;
}
}
}
int my_angel()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s%s",str1,str2);
len1=strlen(str1);
len2=strlen(str2);
for(int i=0; i<len1; i++)
str3[i]=str1[i];
for(int i=0;i<len1;i++)
str1[i]=str3[len1-1-i];
for(int i=0;i<len2;i++)
str3[i]=str2[i];
for(int i=0;i<len2;i++)
str2[i]=str3[len2-1-i];
//memset(ex,0,sizeof(ex));
//memset(ext,0,sizeof(ext));
for(int i=0;i<len2;i++)//memset慢
ext[i]=0;
for(int i=0;i<len1;i++)
ex[i]=0;
EXKMP(str1,str2);
ll ans=0;
//cout<<str1<<endl<<str2<<endl;
for(int i=0;i<len1;i++)
{
ll sum=0;
//if(ex[i]==0)
//continue;
//cout<<ex[i]<<endl;
sum+=(((ll)ex[i]*(ll)(ex[i]+1))/2);
ans+=sum;
ans%=mod;
}
printf("%lld\n",ans);
}
return 0;
}