【4】题解:P4548 [CTSC2006] 歌唱王国【概率生成函数(PGF)】【KMP(Border)】
此文可以当作 PGF 的学习笔记看,之后会同步发布一篇相关内容。
【4】题解:P4548 [CTSC2006] 歌唱王国
评【4】是因为我不会这个东西,研究了一会感觉很难。
字符串
这个东西我之前做过
:::info[概率生成函数]{open}
既然是概率,那么就得有一个概率函数
感觉很唐啊,就像看一些其他的生成函数感觉一点用都没有一样。它有几个比较好的性质:
-
- 考虑转化为期望,就是每一项都乘上其的权值。这题是子串期望,那么就要乘上
i 。你发现,对E(x) 求导久可以得出E'(x)=\sum_{i=1}^{\infty} iP(r=i)x^{i-1} 。此时有E'(1)=\sum_{i=1}^{\infty} iP(r=i)=E(x) 。
即:
:::
构建基础的概率生成函数
显然,最终停止的长度就是当字符串结尾恰好为一个
那么:
这是一个递推的形式。对应回生成函数就是:
其中这里的
求导:
此时:
这个性质就非常好了,先备用。
根据字符串性质推导结尾情况
我们再设一个生成函数
显然,
容易发现:可能出现的情况是在
那么,根据这个
具体怎么做呢?对于
完全一致这个条件是简单的,也就是
综合来看,可得:
也就是每一个位置可能都贡献了答案,可能贡献者为
综合两种 H(x) 求解方法得出问题答案
学会了这两种方法后,考虑如何综合起来,即:
感觉没啥用啊?联立一下:
备用的式子是:
能用吗?将上述式子带入
答案是容易得出的。这个备用式子和带入
:::info[非哈希方法求一个字符串的全部公共前后缀]{open}
注意到,如果一个字符串存在不止一个的公共前后缀,那么短的公共前后缀一定是长的公共前后缀的公共前后缀。这家伙叽里咕噜说什么呢。
具体的,我们有
:::
那么这个问题就做完了。代码比较丑。
::::success[Code]
// Problem: Luogu P4548
// Memory: 250 MiB
// Time: 3000 ms
// Author: Ivan422(Exfish)
// #define FileIO
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fi first
#define se second
#define il inline
bool stMem; double stT=clock();
const int N=1e5+10;
const ll P=10000;
il ll qp(ll a,ll b=P-2){
ll res=1;
for(;b;b>>=1,a=(a*a)%P) if(b&1) res=(res*a)%P;
return res;
}
// ---------------------------------------------------- //
int n, m, s[N], now_border[N]; ll pw[N];
vector<int> border_length;
// ---------------------------------------------------- //
il void solve(){
cin>>m; border_length.clear();
for(int i=1;i<=m;++i) cin>>s[i], now_border[i]=0;
int checked=0;
for(int i=2;i<=m;++i){
while(checked&&s[i]!=s[checked+1]) checked=now_border[checked];
if(s[i]==s[checked+1]) ++checked;
now_border[i]=checked;
}
border_length.push_back(m);
while(checked)
border_length.push_back(checked),
checked=now_border[checked];
ll ans=0;
for(auto t:border_length) (ans+=pw[t])%=P;
string res=to_string(ans);
while(res.size()<4) res="0"+res;
cout<<res<<"\n";
return;
}
// ---------------------------------------------------- //
bool edMem;
int main(){
#ifdef FileIO
freopen("file.in","r",stdin);
freopen("file.out","w",stdout);
#endif
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T=1; cin>>n>>T; pw[0]=1;
for(int i=1;i<=1e5;++i) pw[i]=pw[i-1]*n%P;
while(T--) solve();
cerr<<"\n";
cerr<<"[Info] End Of Running. \n";
cerr<<" Time Used : "<<(clock()-stT)/CLOCKS_PER_SEC*1000.00<<" ms\n";
cerr<<" Memory Used : "<<(&stMem-&edMem)/1048576.00<<" Mib\n";
return 0;
}
::::