A Secret
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 256000/256000 K (Java/Others)Total Submission(s): 1909 Accepted Submission(s): 701
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.
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.
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.
The answer may be very large, so the answer should mod 1e9+7.
Sample Input
2 aaaaa aa abababab aba
Sample Output
13 19Hintcase 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 = (3*3+3*2+4*1)%1000000007.
解:翻转两个字符串,做KMP的过程中记录s2在s1中的匹配成功次数,枚举每一段长度,这段长度的前缀长度+=这段长度的出现次数
#include <iostream>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e6+10;
const LL mod = 1e9+7;
char str1[N], str2[N];
int len1, len2, nex[N];
LL ans[N];
void getnext()
{
int j=0, k=-1;
nex[0]=-1;
while(j<len2)
{
if(k==-1||str2[j]==str2[k]) nex[++j]=++k;
else k=nex[k];
}
return ;
}
void kmp()
{
int j=0, k=0;
while(j<len1)
{
if(k==-1||str1[j]==str2[k])j++,k++;
else k=nex[k];
if(k!=-1)
{
ans[k]++;
if(k==len2) k=nex[k];
}
}
return ;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%s %s", str1, str2);
len1=strlen(str1), len2=strlen(str2);
reverse(str1,str1+len1),reverse(str2,str2+len2);
getnext();
memset(ans,0,sizeof(ans));
kmp();
for(int i=len2;i>=1;i--)
{
if(nex[i]!=-1) ans[nex[i]]+=ans[i];
}
LL sum=0;
for(LL i=1; i<=len2; i++) sum=(sum+ans[i]*i)%mod;
printf("%lld\n",sum);
}
return 0;
}