P1316 题解
很神的容斥题!
假设有一个长度为
如何计算出现的方案数?首先对于没有被
最后除以
#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;
}