A Secret
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 256000/256000 K (Java/Others)
Total Submission(s): 3911 Accepted Submission(s): 1352
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 = (3*3+3*2+4*1)%1000000007.
题意
给你两个串 问你第二个串在第一个串每个后缀出现的长度乘上次数 的和
首先我们怎么思考这个问题?我们可以由hdoj3336知道 是能通过KMP算法的Next数组求得所有前缀出现的次数的
怎么求呢?我们这样想 你让KMP扫的过程中记录每个点被匹配的次数
然后我们知道 Next数组的值代表前面和后面一段相等 也就是说这个段 你在匹配的过程中是匹配了两次
所以你要对所有的 ans[Next[j]] += ans[j];由爸爸推儿子的次数
然后我们就可以想当然的求解了
但是这题是后缀
所以我们需要把第一个串和第二个串同时逆置 那么题目就转换过来了
/*
hdoj 6153
*/
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
//#define dbg(x) cout<<#x<<" = "<< (x)<< endl
const int MAX_N = 1000024;
int Next[MAX_N];
long long ans[MAX_N];
char str[MAX_N],mo[MAX_N];
int n2,n1;
void getnext(){
int i = 0,j=-1;
while(i<n2){
if(j==-1||mo[i]==mo[j]) {++i,++j,Next[i] = j;}
else j = Next[j];
}
return ;
}
void kmp(){
int i = 0,j = 0;
while(i<n1){
if(j==-1||str[i]==mo[j]) i++,j++,ans[j]++;
else j = Next[j];
}
}
int main(){
int t;
scanf("%d",&t);
while(t--){
memset(ans,0,sizeof(ans));
scanf("%s",str);
scanf("%s",mo);
strrev(str);
strrev(mo);
n1 = strlen(str);
n2 = strlen(mo);
Next[0] = -1;
getnext();
kmp();
long long ans_tmp = 0;
for(int i = n2;i>=1;i--)
ans[Next[i]] += ans[i];
for(int i = 1;i<=n2;i++){
// dbg(ans[i]);
ans_tmp+=1LL*ans[i]%1000000007*(i)%1000000007;
ans_tmp%=1000000007;
}
printf("%lld\n",ans_tmp);
}
return 0;
}