A Secret
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.
Source
2017中国大学生程序设计竞赛 - 网络选拔赛
题意好理解,就是那s2在s1中的匹配次数,然后少一位就是(s2+1)在 s1的匹配次数,分别乘于子串s2匹配长度相加
KMP:
#include<bits/stdc++.h>
using namespace std;
int nex[1000009];
void getnext(string a)
{
int len=a.length();
int i=0;
int j=-1;
nex[0]=-1;
while(i<len)
{
if(j==-1||a[i]==a[j])
{
i++;j++;
nex[i]=j;
}
else j=nex[j];
}
}
long long vi[1000009];
void kmp(string a,string b)
{
getnext(b);
int lenb=b.length();
int len=a.length();
int i=0,j=0;
while(i<len)
{
if(j==-1||a[i]==b[j])
{
i++;j++;
}
else j=nex[j];
vi[j]++;
if(j==lenb)
{
j=nex[j];
//vi[j]++;
}
}
}
int main()
{ ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
string a,b;
cin>>a>>b;
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
memset(vi,0,sizeof(vi));
kmp(a,b);
long long ans=0;
for(int i=b.length();i>0;i--)
{
vi[nex[i]]+=vi[i]; //刚开始理解错了,就是把i位往前推的每一位加上后面的,是一段,不是就nex[i]这个点加
ans=(ans+vi[i]*i)%1000000007;
}
cout<<ans<<endl;
}
return 0;
}
exkmp :
占位,正在学习。。。。