类型:KMP【经典】
题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4629
来源: ZOJ 10th Anniversary Contest
思路:以S串为原串,T串为模式串,做两次KMP运算,分别求出在原串中以长度为i的前缀和后缀的数量
!!!如果前缀串中包含部分前缀,需要对其累加
如:S = a a a a a
1 2 3 4 4
T = a a a a
next[4] = 3,将前缀串长度为3的个数累加,依次计算所有含前缀串的子串
// zoj 3587 Marlon's String
// wa wa ac 30ms 2724kb
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
#define FOR(i,a,b) for(i = (a); i < (b); ++i)
#define FORE(i,a,b) for(i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(i = (a); i > (b); --i)
#define FORDE(i,a,b) for(i = (a); i >= (b); --i)
#define max(a,b) ((a) > (b)) ? (a) : (b)
#define min(a,b) ((a) < (b)) ? (a) : (b)
#define CLR(a,b) memset(a,b,sizeof(a))
#define PB(x) push_back(x)
const int MAXN = 100010;
char st[MAXN], sp[MAXN];
int n, cnt, len, m;
long long p[MAXN], first[MAXN], last[MAXN];
void next() {
int k = 0, i;
p[1] = 0;
FORE(i, 2, m) {
while(k > 0 && sp[i] != sp[k + 1])
k = p[k];
if(sp[k + 1] == sp[i])
k = k + 1;
p[i] = k;
}
}
int kmp(int sign) {
int k = 0, i;
FORE(i, 1, len) {
while(k > 0 && st[i] != sp[k + 1])
k = p[k];
if(sp[k + 1] == st[i]) {
(sign == 1) ? ++first[k + 1] : ++last[k + 1];
k = k + 1;
}
if(k == m)
k = p[k];
}
return cnt;
}
int main() {
int i;
scanf("%d", &n);
while(n--) {
scanf("%s %s", st + 1, sp + 1);
len = strlen(st + 1);
m = strlen(sp + 1);
CLR(first, 0), CLR(last, 0);
CLR(p, 0);
next();
kmp(1);
FORDE(i, m, 1)
if(p[i] != 0)
first[p[i]] += first[i];
char tmp;
FORE(i, 1, len / 2)
swap(st[i], st[len - i + 1]);
// tmp = st[i], st[i] = st[len - i + 1], st[len - i + 1] = tmp;
FORE(i, 1, m / 2)
swap(sp[i], sp[m - i + 1]);
// tmp = sp[i], sp[i] = sp[m - i + 1], sp[m - i + 1] = tmp;
CLR(p, 0);
next();
kmp(0);
FORDE(i, m, 1)
if(p[i] != 0)
last[p[i]] += last[i];
long long end = 0;
FORE(i, 1, m - 1)
end += (long long)(first[i] * last[m - i]);
cout<<end<<endl;
}
return 0;
}
/*
2
abcdababecd
abcd
aa
aa
*/