HDU-6153 A Secret (KMP)
题目
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.
题意
一共T组数据,每组数据给出s1、s2两个字符串。要你求s2所有后缀在s1中的匹配值与其相应的长度相乘再将所有结果相加。
思路
将两个字符串都反转,这样题目就变成了求前缀匹配了,这时候是要在kmp_count的循环中匹配时对应前缀位置的匹配数目记录在数组中。
然后在计算答案时,在前缀匹配数组中求后缀和。
AC代码
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6+5;
const int MOD = 1e9+7;
char s1[MAXN], s2[MAXN];
int ans[MAXN];
void kmp_pre(char x[], int next[]) {
int i, j;
j = next[0] = -1;
i = 0;
int m = strlen(x);
while(i < m) {
while(-1 != j && x[i] != x[j]) j = next[j];
next[++i] = ++j;
}
}
void KMP_Count(char x[], char y[], int next[]) { //s2,s1
int i, j;
i = j = 0;
int m = strlen(x), n = strlen(y);
while(i <= n) {
if(i == n) {
int l = 5;
}
while(-1 != j && y[i] != x[j]) {
ans[j]++;
j = next[j];
}
i++;
j++;
if(j >= m) {
ans[m]++;
j = next[j];
}
}
}
int next1[MAXN];
int next2[MAXN];
int main() {
// freopen("RAW/in", "r", stdin);
// freopen("RAW/out", "w", stdout);
int T;
scanf("%d", &T);
while(T--) {
memset(ans, 0, sizeof(ans));
memset(next1, 0, sizeof(next1));
memset(next2, 0, sizeof(next2));
scanf("%s%s", s1, s2);
int lenS1 = strlen(s1), lenS2 = strlen(s2);
for(int i = 0; i < lenS1/2; i++) {
swap(s1[i], s1[lenS1-i-1]);
}
for(int i = 0; i < lenS2/2; i++) {
swap(s2[i], s2[lenS2-i-1]);
}
// printf("%s\n%s\n", s1, s2);
kmp_pre(s1, next1);
kmp_pre(s2, next2);
KMP_Count(s2, s1, next2);
long long num = 0;
// printf("%d\n", ans[lenS2]);
for(int i = lenS2-1; i >= 1; i--) {
ans[i] += ans[i+1];
if(ans[i] >= MOD) ans[i] -= MOD;
}
for(int i = 1; i <= lenS2; i++) {
num += (long long)i*ans[i]%MOD;
if(num >= MOD) num -= MOD;
}
printf("%lld\n", num%MOD);
// for(int i = 0; i <= lenS1; i++) {
// printf("%d ", next1[i]);
// }
// printf("\n");
// for(int i = 0; i <= lenS2; i++) {
// printf("%d ", next2[i]);
// }
// printf("\n\n");
}
return 0;
}