@(ACM题目)[字符串, kmp, 扩展kmp]
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.
题目分析
在上一篇中我们使用KMP加一点前缀和的技巧得到了答案,实际上我们可以使用扩展KMP,那么就变成了模板题。
同样reverse两个字符串。
extendi
代表模式串
P
的后缀
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 1e6 + 5;
char s1[maxn], s2[maxn];
struct ExtendKMP
{
//模式串P(Pattern)长度m,文本串T(Text)长度n
//nxt[i]:T[i..n-1]与T的LCP长度
//extend[i]:P[i..m-1]与T的LCP长度
int nxt[maxn], extend[maxn];
void getNext(char *P)
{
int m = strlen(P);
nxt[0] = m;
int i = 0;
while(P[i] == P[i+1]) ++i;
nxt[1] = i;
int id = 1;
for(i = 2; i < m; ++ i)
{
if(nxt[i-id] + i < id + nxt[id]) nxt[i] = nxt[i-id];
else
{
int j = nxt[id] + id - i;
if(j < 0) j = 0;
while(i+j < m && P[j] == P[j+i]) ++j;
nxt[i] = j;
id = i;
}
}
}
void getExtend(char *P, char *T)
{
int m = strlen(P);
int n = strlen(T);
getNext(T);
int i = 0;
while(i < m && i < n && P[i] == T[i]) ++i;
extend[0] = i;
int id = 0;
for(int i = 1; i < m; ++i)
{
if(nxt[i-id]+i < extend[id]+id) extend[i] = nxt[i-id];
else
{
int j = extend[id] + id - i;
if(j < 0) j = 0;
while(i + j < m && j < n && P[j+i] == T[j]) ++j;
extend[i] = j;
id = i;
}
}
}
}exKMP;
const LL M = 1e9 + 7;
int main()
{
int T;
cin >> T;
while(T--)
{
scanf("%s%s", s1, s2);
int n = strlen(s1);
int m = strlen(s2);
reverse(s1, s1 + n);
reverse(s2, s2 + m);
exKMP.getExtend(s1, s2);
LL res = 0;
for(int i = 0; i < n; ++i)
{
LL len = exKMP.extend[i];
res = (res + len*(len+1)/2) % M;
}
cout << res << endl;
}
return 0;
}