码迷,mamicode.com
首页 > 其他好文 > 详细

hdu6153KMP

时间:2017-08-19 23:45:28      阅读:352      评论:0      收藏:0      [点我收藏+]

标签:枚举   pre   otto   code   accept   inpu   title   ini   伪代码   

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

标签:枚举   pre   otto   code   accept   inpu   title   ini   伪代码   

原文地址:http://www.cnblogs.com/mfys/p/7398193.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!