很神的容斥题!
假设有一个长度为 的子串 ,假设它在字符串中出现了 次,出现的开头位置集合为 (显然有 ),那么它对答案的贡献系数为 。
如何计算出现的方案数?首先对于没有被 碰到的点,可以取 种字符。对于被 碰到的点,如果被碰到多次,那么这两个位置就必须相同,用并查集维护。最后贡献即为 ,其中 表示连通块个数。
最后除以 计算期望即可。由于 ,所以复杂度为 。
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int MOD(1e9+7);
int n, m, ans; int f[21], c[21];
int find(int x){return f[x] == x ? x : f[x] = find(f[x]);}
int qpow(int x, int k=MOD-2){int res(1); for (; k; k>>=1, (x*=x)%=MOD) if (k&1) (res*=x)%=MOD; return res;}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int x(1); x<=n; ++x){
for (int i(1); i<(1<<(n-x+1)); ++i){
memset(c, -1, sizeof(c)); iota(f, f+x+1, 0);
for (int j(0); j<n-x+1; ++j) if (i>>j&1){
for (int k(0); k<x; ++k) if (~c[j+k]) f[find(k)] = find(c[j+k]); else c[j+k] = k;
}
int nw(0); for (int j(0); j<x; ++j) nw += f[j] == j; for (int j(0); j<n; ++j) nw += c[j] == -1; nw = qpow(m, nw);
(ans += __builtin_parity(i) ? nw : MOD-nw) %= MOD;
}
}
cout << ans*qpow(qpow(m, n))%MOD;
return 0;
}