原題
A Secret
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
2aaaaa
aa
abababab
aba
Sample Output
1319
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中國大學生程序設計競賽 - 網絡選拔賽題意
涉及知識及算法
代碼
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MOD = 1000000007;
const int MAXL=1e6+5;
char str1[MAXL],str2[MAXL];
int extend[MAXL],Next[MAXL];
int str1l,str2l;
//模式串自己和自己匹配
void GetNext()
{
//a爲已匹配位置之首,p爲已匹配位置之尾
int a=0,p=0;
//從下標爲0開始的匹配就是自己的長度
Next[0]=str2l;
//從下標爲1開始匹配
for(int i=1;i<str2l;i++)
{
//i>=p作用:舉個例子,母串無一字符與模式串相同
//i大於p或可以繼續往後匹配
if(i>=p||i+Next[i-a]>=p)
{
if(i>=p)
{
//更新尾位置
p=i;
}
//往後匹配並更新尾位置
while(p<str2l&&str2[p]==str2[p-i])
{
p++;
}
Next[i]=p-i;
//更新首位置
a=i;
}
else
{
Next[i]=Next[i-a];
}
}
}
//母串和模式串匹配,與求Next過程類似
void GetExtend()
{
int a=0,p=0;
GetNext();
for(int i=0;i<str1l;i++)
{
if(i>=p||i+Next[i-a]>=p)
{
if(i>=p)
{
p=i;
}
while(p<str1l&&p-i<str2l&&str1[p]==str2[p-i])
{
p++;
}
extend[i]=p-i;
a=i;
}
else
{
extend[i]=Next[i-a];
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
int n;
scanf("%d",&n);
getchar();
while(n--)
{
gets(str1);
str1l=strlen(str1);
reverse(str1,str1+str1l);
gets(str2);
str2l=strlen(str2);
reverse(str2,str2+str2l);
GetExtend();
long long sum=0;
for(int i=0;i<str1l;i++)
{
sum=(sum+((long long)extend[i]*(extend[i]+1)/2)%MOD)%MOD;
}
printf("%lld\n",sum);
}
return 0;
}