题解:P11749 「TPOI-1C」Standard Problem.
GUO120822
·
·
题解
下文令 A\&B 表示 A 与 B 拼接之后,开头在 A 结尾在 B 的方案数。
首先,有递推公式:
S^1=1
S^2=S^1+2+1\&2
S^3=S^2+3+2\&3+1\&2\&3
\dots
差分,得到:
S^2-S^1=2+1\&2
S^3-S^2=3+2\&3+1\&2\&3
\dots
S^k-S^{k-1}=k+(k-1)\&k+\dots+1\&2\&\dots\&k
显然,这些东西的和加上 S^1 就是答案。
首先考虑 1,2,3,\dots,k 都长一样,所以长度相同的 1,2,3,\dots,k,1\&2,2\&3,\dots,(k-1)\&k 诸如此类都一样。
再考虑一个惊人的结论:
1\&2\&3=1\&2\&3\&4=1\&2\&3\&4\&5=\dots
这是为啥呢?因为 s 和 ss 和 sss 回文等价。
所以对于两边的每一对位置,中间都是等价的。
处理出 S1,S2,S3。
最后答案:
最后那个东西咋来的?我们要求 $1\&2\&3$。
也就是 $S^3-S^2-(S^2-S^1)=S^3-2\times S^2+S^1$。
时间复杂度:$\mathcal O(n)$。使用马拉车。
```cpp
#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;
}
```