KMP,正着处理一遍,反着处理一遍,但是用递归的方式一个一个统计会超时,最后累加一下比较好= =
#include <cstdio>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <deque>
#include <algorithm>
using namespace std;
void getnext(char *s, int *next)
{
int i = 0, j = -1, l = strlen(s);
next[0] = -1;
while (i < l)
{
if (j == -1 || s[i] == s[j])
{
i++; j++;
next[i] = j;
//if (s[i] == s[j]) next[i] = j;
//else next[i] = -1;
}
else j = next[j];
}
}
void find(char *s, char *t, int *next, int *a)
{
int l = strlen(s), n = strlen(t), i = 0, j = 0;
while (i < l && j < n)
{
if (j == -1 || s[i] == t[j])
{
i++; j++;
a[j]++;
}
else j = next[j];
}
}
const int maxn = 100005;
int T, n, l;
char s[maxn], t[maxn];
int next[maxn], a[maxn], b[maxn];
long long ans;
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%s%s", s, t);
l = strlen(s); n = strlen(t);
t[n] = '$'; t[n+1] = 0;
memset(a, 0, sizeof(a));
getnext(t, next);
find(s, t, next, a);
for (int i=n;i>=1;i--)
if (next[i] != -1)
a[next[i]] += a[i];
for (int i=0;i<l/2;i++) swap(s[i], s[l-i-1]);
for (int i=0;i<n/2;i++) swap(t[i], t[n-i-1]);
memset(b, 0, sizeof(b));
getnext(t, next);
find(s, t, next, b);
for (int i=n;i>=1;i--)
if (next[i] != -1)
b[next[i]] += b[i];
ans = 0;
for (int i=1;i<n;i++)
ans += (long long)a[i] * b[n-i];
printf("%lld\n", ans);
}
return 0;
}