hdu-6153

来源:互联网 发布:双十一淘宝营业额2017 编辑:程序博客网 时间:2024/06/05 06:45

A Secret

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


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


kmp算法,主要要理解next数组的应用,kmp还是要理解透,对于这道题,因为要求匹配的次数和字符长度,先反转字符串,一个个去比较,每个的字符贡献为1


代码:

#include<cstdio>#include<cstring>#include<string>#include<iostream>#include<algorithm>using namespace std;#define MOD 1000000007typedef long long ll;const int maxn=1e6+7;ll t,la,lb,i,j,k;char sa[maxn],sb[maxn];ll nex[maxn],val[maxn];void getnext(){    memset(nex,0,sizeof(nex));    memset(val,0,sizeof(val));    nex[0]=-1;    for(i=0;i<lb;i++)    {        j=nex[i];        val[i+1]=i+1;        while(j>-1)        {            if(sb[j]==sb[i]) {nex[i+1]=j+1,val[i+1]+=val[j+1],val[i+1]%=MOD;break;}            j=nex[j];        }    }}ll matchfind(){    ll ans=0;    k=0;    for(i=0;i<la;i++)    {        j=k;        for(k=0;j>=0;j=nex[j])        {            if(sa[i]==sb[j])            {                k=j+1;                break;            }        }        ans=(ans+val[k])%MOD;    }    return ans;}int main(){    scanf("%lld",&t);    while(t--)    {        scanf("%s %s",sa,sb);        la=strlen(sa),lb=strlen(sb);        reverse(sa,sa+la),reverse(sb,sb+lb);        getnext();        printf("%lld\n",matchfind());    }    return 0;}