下文令 表示 与 拼接之后,开头在 结尾在 的方案数。
首先,有递推公式:
差分,得到:
显然,这些东西的和加上 就是答案。
首先考虑 都长一样,所以长度相同的 , 诸如此类都一样。
再考虑一个惊人的结论:
这是为啥呢?因为 和 和 回文等价。
所以对于两边的每一对位置,中间都是等价的。
处理出 。
最后答案:
。
最后那个东西咋来的?我们要求 。
也就是 。
时间复杂度:。使用马拉车。
#include<bits/stdc++.h>
using namespace std;
/*
*/
struct FSI{
template<typename T>
FSI& operator >> (T &res){
res=0;T f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){res=res*10+ch-'0';ch=getchar();}
res*=f;
return *this;
}
}scan;
typedef long long ll;
const int N=9e6+10,M=2*N,mod=998244353;
int T,n,i;
string s;
char t[M];
int p[M];
ll S1,S2,S3,ans,k;
ll manacher(string s)
{
int i,n=s.size(),mid=0,r=0,m=0;
ll ans=0;
t[++m]='#';
for (i=0;i<n;i++)
{
t[++m]=s[i];
t[++m]='#';
}
for (i=1;i<=m;i++)
{
if (i<=r) p[i]=min(p[2*mid-i],r-i+1);
else p[i]=1;
while (i-p[i]>=1&&i+p[i]<=m&&t[i-p[i]]==t[i+p[i]]) p[i]++;
ans=(ans+p[i]/2)%mod;
if (i+p[i]-1>r) r=i+p[i]-1,mid=i;
}
return ans;
}
void work()
{
cin>>n>>k>>s;
S1=manacher(s);
S2=manacher(s+s);
S3=manacher(s+s+s);
ans=(S1+(k-1)*((S2-S1+mod)%mod)%mod+(k-1)*(k-2)/2%mod*((S3-2*S2+S1+mod+mod)%mod)%mod)%mod;
cout<<ans<<"\n";
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>T;
while (T--) work();
return 0;
}