题目:http://acm.hdu.edu.cn/showproblem.php?pid=6153
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
题目的大意是,有两个字符串(s[],p[]),问p[]所有的后缀在s[]中出现的次数和后缀长度乘积的总和是多少?
其实,这是一个扩展KMP的应用。(扩展KMP求的是extend[i]=s[i…n]与p[]的最长公共前缀)只需要把,s[]和p[]都翻转一下,后缀就是前缀了。所以求出extend[]就是最长的公共后缀了。既然是,最长的后缀,那么,其他的后缀也都包含在里面了所以就是extend[i]*(extend[i]+1)/2了。
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<algorithm>
using namespace std;
const int maxn = 1e6+5;
const long mod = 1e9+7;
char s[maxn],p[maxn];
int next[maxn],extend[maxn];void preEKMP(char x[], int m) {next[0] = m;int j = 0;while (j + 1 < m && x[j] == x[j + 1]) {j++;}next[1] = j;int k = 1;for (int i = 2; i < m; i++) {int p = next[k] + k - 1;int L = next[i - k];if (i + L < p + 1) {next[i] = L;} else {j = std::max(0, p - i + 1);while (i + j < m && x[i + j] == x[j]) {j++;}next[i] = j;k = i;}}
}void EKMP(char x[], int m, char y[], int n) {preEKMP(x, m, next);int j = 0;while (j < n && j < m && x[j] == y[j]) {j++;}extend[0] = j;int k = 0;for (int i = 1; i < n; i++) {int p = extend[k] + k - 1;int L = next[i - k];if (i + L < p + 1) {extend[i] = L;} else {j = std::max(0, p - i + 1);while (i + j < n && j < m && y[i + j] == x[j]) {j++;}extend[i] = j;k = i;}}
}int main(){int N;long long ans;scanf("%d",&N); while(N--){ ans = 0;memset(s,'\0',sizeof(s));memset(p,'\0',sizeof(p)); scanf("%s%s",s,p);int s_len = strlen(s);int p_len = strlen(p); reverse(s,s+s_len);reverse(p,p+p_len);EKMP(p,p_len,s,s_len);for(int i=0;i<s_len;i++){if(m[i]){ans=(ans+(1ll*extend[i]*(extend[i]+1)/2)%mod)%mod;}}printf("%lld\n",ans);} }