传送门:HDU 6155
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.
Sample Input
2
aaaaa
aa
abababab
aba
Sample Output
13
19
Hint
case 2:
Suffix(S2,1) = “aba”,
Suffix(S2,2) = “ba”,
Suffix(S2,3) = “a”.
N1 = 3,
N2 = 3,
N3 = 4.
L1 = 3,
L2 = 2,
L3 = 1.
ans = (33+32+4*1)%1000000007.
题解:
首先kmp是从头往后进行比对,所以题目给的S1,S2需要全部倒置后再kmp。对于kmp的相关改动为:枚举时的主串长度+1,j调到next[j]之前都要用数组a记录长度为j的匹配长度a[j]++,最后从后往前处理数组a,a[i]+=a[i+1],就得到了S2中每个后缀子串在S1中出现的次数a[i],再乘上每个后缀子串的长度,也就是i,相加取余得ans。
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N=1100000;
const int mod=1e9+7;
char s1[N],s2[N];
int t;
int nexts[N];
ll ans[N];
void get_next()
{
int len=strlen(s2);
nexts[0]=-1;
int j=0,k=-1;
while(j<len)
{
if(k==-1||s2[j]==s2[k])
{
j++;
k++;
nexts[j]=k;
}
else k=nexts[k];
}
}
void kmp()
{
get_next();
int len1=strlen(s1),len2=strlen(s2);
int i=0,j=0;
for(i=0;i<=len1;i++)
{
while(j>0&&s1[i]!=s2[j])
{
ans[j]++;
j=nexts[j];
}
if(s1[i]==s2[j])
{
j++;
}
if(j==len2)
{
ans[j]++;
j=nexts[j];
}
}
}
int main()
{
scanf("%d",&t);
while(t--)
{
memset(ans,0,sizeof(ans));
scanf("%s",s1);
scanf("%s",s2);
int len1=strlen(s1),len2=strlen(s2);
reverse(s1,s1+len1);
reverse(s2,s2+len2);
kmp();
ll sum=0;
for(int i=len2;i>0;i--)
{
ans[i]=(ans[i]+ans[i+1])%mod;
sum=(sum+ans[i]*i%mod)%mod;
}
printf("%I64d\n",sum);
}
return 0;
}