题意:
Return the amount of tetrad (a,b,c,d) which satisfy Sa..b + Sc..d = T , a≤b and c≤d.
思路:
正反两次kmp,匹配出最长前后缀的匹配次数.再进行统计.
注意的是统计的方法:
因为记录的是最长前后缀, 而统计时要将所有的前后缀都要算进去, 相当于每加一次, 都要沿着next回溯到-1. 有一种方法就是不断地向前累加"最长前后缀匹配次数"数组, 用迭代的方式节省不必要的循环.
坑:
注意下标:next下标小一.....
#include <cstdio>
#include <cstring>
using namespace std;
int const MAXN = 100005;
char s[MAXN],t[MAXN];
long long ord[MAXN],rev[MAXN],tmp[MAXN];
int ns,nt,next[MAXN];
void prekmp(char B[])
{
next[0] = -1;
int j = -1;
for(int i=1;B[i];i++)
{
while(j!=-1 && B[j+1]!=B[i]) j = next[j];
if(B[j+1]==B[i]) j++;
next[i] = j;
}
}
void kmp(char A[], char B[], long long ans[])
{
memset(ans,0,sizeof(long long)*MAXN);
int j = -1;
for(int i=0;A[i];i++)
{
while(j!=-1 && B[j+1]!=A[i]) j = next[j];
if(B[j+1]==A[i]) j++;
ans[j+1]++;
if(!B[j+1]) j = next[j];
}
}
void reverse(char src[], int n)
{
char ch;
for(int i=0;i<(n>>1);i++)
{
if(src[n-1-i] != src[i])
{
ch = src[n-1-i];
src[n-1-i] = src[i];
src[i] = ch;
}
}
}
void get_ans(long long ans[], long long src[])
{
for(int i=nt;i;i--)
{
ans[i] = src[i];
src[next[i-1]+1] += src[i];//index error
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s%s",s,t);
ns = strlen(s);
nt = strlen(t);
prekmp(t);
kmp(s,t,tmp);
get_ans(ord,tmp);
reverse(s,ns);
reverse(t,nt);
prekmp(t);
kmp(s,t,tmp);
get_ans(rev,tmp);
long long ans = 0;
for(int i=1;i<nt;i++)
{
ans += ord[i]*rev[nt-i];
}
printf("%lld\n",ans);
}
}