您的位置:首页 > 其它

HDU 6153 扩展kmp

2017-08-21 16:54 274 查看

A Secret

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


[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
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.

[align=left]Sample Input[/align]

2
aaaaa
aa
abababab
aba

[align=left]Sample Output[/align]

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 模板题

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
#define mod 1000000007
typedef long long ll;
int T;
char s[1000006],t[1000006];
int extend[1000006],nex[1000006];
void pre_ex_kmp(char x[],int m,int nex[])
{
nex[0]=m;
int j=0;
while(j+1<m&&x[j]==x[j+1])
j++;
nex[1]=j;
int k=1;
for(int i=2; i<m; i++)
{
int p=nex[k]+k-1;
int L=nex[i-k];
if(i+L<p+1)
nex[i]=L;
else
{
j=max(0,p-i+1);
while(i+j<m&&x[i+j]==x[j])
j++;
nex[i]=j;
k=i;
}
}
}
void ex_kmp(char x[],int m,char y[],int n,int nex[],int extend[])
{
pre_ex_kmp(x,m,nex);
int j=0;
while(j<n&&j<m&&x[j]==y[j])
j++;
extend[0]=j;
int k=0;
for(int i=1; i<n; i++)
{
int p=extend[k]+k-1;
int L=nex[i-k];
if(i+L<p+1)
extend[i]=L;
else
{
j=max(0,p-i+1);
while(i+j<n&&j<m&&y[i+j]==x[j])
j++;
extend[i]=j;
k=i;
}
}
}
int main()
{
scanf("%d",&T);
while(T--)
{
memset(extend,0,sizeof(extend));
memset(nex,0,sizeof(nex));
scanf("%s",s);
scanf("%s",t);
int len1=strlen(s);
int len2=strlen(t);
reverse(s,s+len1);
reverse(t,t+len2);
ex_kmp(t,len2,s,len1,nex,extend);
ll ans=0;
ll n;
for(int i=0; i<len1; i++)
{
if(extend[i])
{
n=extend[i]%mod;
ans=ans+(n*(n+1)/2)%mod;
ans%=mod;

}
}
cout<<ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: