题意:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6153
Ni表示S串中出现了多少次T[i,len],Li表示T[i,len]的长度,求Li和Ni的乘积和。
思路:
把S和T都倒过来拓展KMP即可。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL MOD = 1e9 + 7;
const int MAXN = 1e6 + 10;
int nxt[MAXN], ext[MAXN];
void getnext(char *T) {
int i, len = strlen(T), x = 1;
nxt[0] = len;
for (i = 0; i < len - 1 && T[i] == T[i + 1]; i++);
nxt[1] = i;
for (int k = 2; k < len; k++) {
int p = x + nxt[x] - 1, L = nxt[k - x];
if (k - 1 + L >= p) {
int j = max(p - k + 1, 0);
while (k + j < len && T[k + j] == T[j]) j++;
nxt[k] = j, x = k;
}
else nxt[k] = L;
}
}
void getextand(char *S, char *T, int ls, int lt){
memset(nxt, 0, sizeof(nxt));
getnext(T);
int x = 0, MinLen = min(ls, lt);
while (x < MinLen && S[x] == T[x]) x++;
ext[0] = x, x = 0;
for (int k = 1; k < ls; k++) {
int p = x + ext[x] - 1, L = nxt[k - x];
if ((k - 1) + L >= p) {
int j = max(p - k + 1, 0);
while (k + j < ls && j < lt && S[k + j] == T[j]) j++;
ext[k] = j; x = k;
}
else ext[k] = L;
}
}
int cnt[MAXN];
char s[MAXN], t[MAXN], tmp[MAXN];
int main() {
//freopen("in.txt", "r", stdin);
int T;
scanf("%d", &T);
while (T--) {
scanf("%s%s", s, t);
memset(cnt, 0, sizeof(cnt));
int ls = strlen(s), lt = strlen(t);
strcpy(tmp, s);
for (int i = 0; i < ls; i++) s[i] = tmp[ls - i - 1];
strcpy(tmp, t);
for (int i = 0; i < lt; i++) t[i] = tmp[lt - i - 1];
//cout << s << endl;
//cout << t << endl;
getextand(s, t, ls, lt);
for (int i = 0; i < ls; i++) ++cnt[ext[i]];
for (int i = lt - 1; i >= 1; i--) cnt[i] += cnt[i + 1];
LL ans = 0;
for (int i = 1; i <= lt; i++)
ans = (ans + (LL)cnt[i] * i % MOD) % MOD;
printf("%I64d\n",ans);
}
return 0;
}