1. 程式人生 > >HDU 6153 A Secret(擴展kmp)

HDU 6153 A Secret(擴展kmp)

出現的次數 include for %d target recommend lar out big

A Secret

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

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. Source 2017中國大學生程序設計競賽 - 網絡選拔賽 Recommend liuyiding | We have carefully selected several similar problems for you: 6160 6159 6158 6157 6156 題目大意: 給你兩個字符串A,B,現在要你求B串的後綴在A串中出現的次數和後綴長度的乘積和為多少。 題解: 擴展KMP模板題,將s和t串都逆序以後就變成了求前綴的問題了,擴展KMP求處從i位置開始的最長公共前綴存於數組,最後通過將數組的值不為0的進行一個等差數列和的和就可以了。
#include<bits/stdc++.h>
using
namespace std; const int mod=1e9+7; const int N = 1000005; int Next[N]; long long ex[N]; //即extand[] char p[N],t[N]; int T; long long ans; void pre() // next[i]: 以第i位置開始的子串 與 T的公共前綴 { int lp=strlen(p); Next[0]=lp; int j=0,k=1; while(j+1<lp && p[j]==p[j+1]) j++; Next[1]=j; for(int i=2; i<lp; i++) { int P=Next[k]+k-1; int L=Next[i-k]; if(i+L<P+1) Next[i]=L; else { j=max(0,P-i+1); while(i+j<lp && p[i+j]==p[j]) j++; // 枚舉(p+1,length) 與(p-k+1,length) 區間比較 Next[i]=j; k=i; } } } void exkmp() { int lp=strlen(p),lt=strlen(t); pre(); //next數組初始化 int j=0,k=0; while(j<lt && j<lp && p[j]==t[j]) j++; ex[0]=j; for(int i=1;i<lt;i++) { int P=ex[k]+k-1; int L=Next[i-k]; if(i+L<P+1) ex[i]=L; else { j=max(0,P-i+1); while(i+j<lt && j<lp && t[i+j]==p[j]) j++; ex[i]=j; k=i; } } } int main() { scanf("%d",&T); while(T--) { scanf("%s%s",&t,&p); int lt=strlen(t); int lp=strlen(p); reverse(p,p+lp); reverse(t,t+lt); exkmp(); ans=0; for(int i=0;i<lt;i++) ans=(ans+(1+ex[i])*ex[i]/2)%mod; printf("%lld\n",ans); } }

HDU 6153 A Secret(擴展kmp)