题意:给你两个字符串,问你这两个字符串中相同的回文子串的乘积和
解题思路:建立两颗树,然后一起遍历这两颗树就行了,因为是回文树的特点,如果当前两棵树都出现了某一回文子串,那么这回文子串的长度-2也一定出现了,按照这个规律,直接dfs遍历
#include<bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef long long LL;
const int maxn = 200000+200;
const int N = 26 ;
const int mod=1e9+7;
struct Palindromic_Tree {
int next[maxn][N] ;//next指针,next指针和字典树类似,指向的串为当前串两端加上同一个字符构成
int fail[maxn] ;//fail指针,失配后跳转到fail指针指向的节点
int cnt[maxn] ;
int num[maxn] ;
int len[maxn] ;//len[i]表示节点i表示的回文串的长度
int S[maxn] ;//存放添加的字符
int last ;//指向上一个字符所在的节点,方便下一次add
int n ;//字符数组指针
int tot ;//节点指针
LL val[maxn];
int newnode ( int l ) {//新建节点
for ( int i = 0 ; i < N ; ++ i ) next[tot][i] = 0 ;
cnt[tot] = 0 ;
num[tot] = 0 ;
val[tot] = 0LL;
len[tot] = l ;
return tot ++ ;
}
void init () {//初始化
tot = 0 ;
newnode ( 0 ) ;
newnode ( -1 ) ;
last = 0 ;
n = 0 ;
S[n] = -1 ;//开头放一个字符集中没有的字符,减少特判
fail[0] = 1 ;
}
int get_fail ( int x ) //get_fail函数就是让找到第一个使得S[n - len[last] - 1] == S[n]的last
{//和KMP一样,失配后找一个尽量最长的
while ( S[n - len[x] - 1] != S[n] ) x = fail[x] ;//如果没有构成回文,那么去找最长的后缀回文子串
return x ;//如果能构成回文,说明可以通过之前的点+一个字符构成新的回文
}
void add ( int c ) {
c -= 'a' ;
S[++ n] = c ;
int cur = get_fail ( last ) ;//通过上一个回文串找这个回文串的匹配位置
if ( !next[cur][c] ) {//如果这个回文串没有出现过,说明出现了一个新的本质不同的回文串
int now = newnode ( len[cur] + 2 ) ;//新建节点
fail[now] = next[get_fail ( fail[cur] )][c] ;//和AC自动机一样建立fail指针,以便失配后跳转
next[cur][c] = now ;
num[now] = num[fail[now]] + 1 ;
}
int pre = cur;
last = next[cur][c];
// if(len[pre] == -1) val[last] = c;
// else val[last] = ( (val[pre] * 10) % mod + (c * pow_mod(10, len[pre]+1) % mod ) % mod + c ) % mod;
cnt[last] ++ ;
}
void count () {
for ( int i = tot - 1 ; i >= 0 ; -- i ) cnt[fail[i]] += cnt[i] ;
//父亲累加儿子的cnt,因为如果fail[v]=u,则u一定是v的子回文串!
}
}a,b;
char s[maxn],t[maxn];
ll ans;
void dfs(int x,int y)
{
for(int i=0;i<26;i++)
{
int tmpa=a.next[x][i];
int tmpb=b.next[y][i];
if(tmpa&&tmpb)
{
ans+=a.cnt[tmpa]*1ll*b.cnt[tmpb];
dfs(tmpa,tmpb);
}
}
}
int main()
{
int cot=0;int tt;
scanf("%d",&tt);
while(tt--)
{
scanf("%s%s",s,t);
ans=0;
a.init();b.init();cot++;
int slen=strlen(s);int tlen=strlen(t);
for(int i=0;i<slen;i++)
a.add(s[i]);
for(int i=0;i<tlen;i++)
b.add(t[i]);
a.count();b.count();
dfs(0,0);
dfs(1,1);
cout<<"Case "<<"#"<<cot<<": "<<ans<<endl;
}
}