hdu6153KMP

Posted Billyshuai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu6153KMP相关的知识,希望对你有一定的参考价值。

A Secret

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


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.
 实际上是枚举第一个字符串 然后看第二个字符串跟他匹配的字符位置最长的地方在哪里
 
 
 伪代码  for(int i=0;i<len;++i)  if(j是跟此时i匹配的最远距离) ans+=f[j]
 
 
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1e6+50;
const int mod=1e9+7;
char chang[N],duan[N];
int nex[N],f[N];
int len1,len2;
void get()
{
    int i=0,j=-1;
    nex[0]=-1;
    while(i<len2)
    {
        if(j==-1||duan[i]==duan[j]) nex[++i]=++j;
        else j=nex[j];
    }
    f[0]=0;
    for(int i=1; i<=len2; ++i) f[i]=(f[nex[i]]+i)%mod;
}
int KMP()
{
    get();
    int i=0,j=0,ans=0;
    while(i<len1)
    {
        while(~j&&chang[i]!=duan[j])
        {
            j=nex[j];
        }
        ++i;++j;
        ans=(ans+f[j])%mod;
        if(j==len2) j=nex[j];

    }
    return ans%mod;
}
int main()
{
    int T;
    for(scanf("%d",&T); T--;)
    {
        scanf("%s %s",chang,duan);
        len1=strlen(chang),len2=strlen(duan);
        for(int i=0; i<len1/2; ++i) swap(chang[i],chang[len1-1-i]);
        for(int i=0; i<len2/2; ++i) swap(duan[i],duan[len2-i-1]);
        printf("%d\n",KMP());
    }
}

 

以上是关于hdu6153KMP的主要内容,如果未能解决你的问题,请参考以下文章

HDU 6153 A Secret (KMP)

hdu6153KMP

HDU 6153 A Secret KMP

HDU 6153 拓展KMP (2017CCPC)

HDU 6153 A Secret(扩展kmp)

HDU 6153 A Secret(扩展KMP模板题)