HDU 6153 拓展KMP (2017CCPC)

时间:2021-02-09 04:20:04

A Secret

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 256000/256000 K (Java/Others)
Total Submission(s): 975    Accepted Submission(s): 372

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.

题意

给你两个字符串A,B,现在要你求B串的后缀在A串中出现的次数和后缀长度的乘积和为多少。

思路

扩展KMP模板题,将s和t串都逆序以后就变成了求前缀的问题了,扩展KMP求处从i位置开始的最长公共前缀存于数组,最后通过将数组的值不为0的进行一个等差数列和的和就可以了。

代码:

 #include <iostream>
#include <string>
#include <string.h>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e6 + ;
const int mod = 1e9 + ;
typedef long long ll;
int cnt[maxn];
char A[maxn],B[maxn];
int Next[maxn],ex[maxn];
ll add(ll n)
{
ll m=((n%mod)*((n+)%mod)/)%mod;
return m;
}
void kmp(char P[])
{
int m=strlen(P);
Next[]=m;
int j=,k=;
while(j+<m&&P[j]==P[j+]) j++;
Next[]=j;
for(int i=; i<m; i++)
{
int p=Next[k]+k-;
int L=Next[i-k];
if(i+L<p+) Next[i]=L;
else
{
j=max(,p-i+);
while(i+j<m&&P[i+j]==P[j])
j++;
Next[i]=j;
k=i;
}
}
} void exkmp(char P[],char T[])
{
int m=strlen(P),n=strlen(T);
kmp(P);
int j=,k=;
while(j<n&&j<m&&P[j]==T[j])
j++;
ex[]=j;
for(int i=; i<n; i++)
{
int p=ex[k]+k-;
int L=Next[i-k];
if(i+L<p+)
ex[i]=L;
else
{
j=max(,p-i+);
while(i+j<n&&j<m&&T[i+j]==P[j])
j++;
ex[i]=j;
k=i;
}
}
} int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s%s",A,B);
int lenA=strlen(A);
int lenB=strlen(B);
reverse(A,A+lenA);
reverse(B,B+lenB);
kmp(B);
memset(Next,,sizeof(Next));
memset(ex,,sizeof(ex));
exkmp(B,A);
ll ans = ;
for(int i=;i<lenA;i++)
{
if(ex[i])
ans=(ans+add(ex[i])%mod)%mod;
}
printf("%lld\n",ans%mod);
}
return ;
}