HDU-6153 A Secret (扩展KMP)

来源:互联网 发布:mac svn客户端 编辑:程序博客网 时间:2024/06/05 17:45

A Secret

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


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
2aaaaaaaabababababa
 

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中国大学生程序设计竞赛 - 网络选拔赛
 

Recommend
liuyiding


题意:
看Hint应该能够知道题目要求什么

分析:
题目要求的是求 b串的后缀与a串的匹配。
所以只要将a和b串翻转,就变成求前缀啦~
接着,去处理b串内部的关系
dp[i+1]=i+1+dp[next[i+1]]
得到这个之后直接去与a串匹配
然后记得取膜就可以了~~~

AC代码:

#include<stdio.h>#include<string.h>#include<vector>#include<algorithm>#define mod 1000000007using namespace std;struct KMP{    char a[2000000],b[2000000];    int nextval[2000000],n,m;    long long dp[2000000];    void init()    {memset(nextval,0,sizeof(nextval));memset(dp,0,sizeof(dp));dp[1]=1;    }    void get_next()    {int j=0;for(int i=1;i<m;i++){    j=nextval[i];    if(j&&b[i]!=b[j])j=nextval[j];    nextval[i+1]=b[i]==b[j]?j+1:0;    dp[i+1]=dp[nextval[i+1]]+i+1;    dp[i+1]%=mod;}    }    long long get_ans()    {long long ans=0;int j=0;for(int i=0;i<n;i++){    while(j&&a[i]!=b[j])j=nextval[j];    if(a[i]==b[j]) j++;    if(j)    {ans+=dp[j];ans%=mod;    }}return ans;    }}T;char a[2000000];int main(){    int t;    scanf("%d",&t);    while(t--)    {scanf("%s",a);int len=strlen(a);for(int i=0,j=len-1;j>=0;j--,i++)    T.a[i]=a[j];T.n=len;//T.a[len]='#';scanf("%s",a);len=strlen(a);for(int i=0,j=len-1;j>=0;j--,i++)    T.b[i]=a[j];T.m=len;T.init();T.get_next();printf("%lld\n",T.get_ans());    }}


 
 

原创粉丝点击