洛谷:P1316 Mivik 写书

凑任务的,别理。

#include <bits/stdc++.h>
#define mod 1000000007ll
using namespace std;
using ll = long long;
int n;
ll m;
ll qp(ll x, ll y) {
	ll ans = 1;
	while (y) {
		if (y & 1) ans = ans * x % mod;
		y >>= 1;
		x = x * x % mod;
	}
	return ans;
}
ll ans;
int fa[25];
int getfa(int x) {
	return x == fa[x] ? x : fa[x] = getfa(fa[x]);
}
void sol(int x) {
	int a = (1 << (n - x + 1)), b = (1 << x) - 1; //a 是枚举出现位置,b 相当于一个掩膜
	for (int i = 1; i < a; ++i) {
		int c = 0, tot = 0;
		for (int j = 0; j < x; ++j) fa[j] = j;
		for (int j = 0; j < n; ++j) {
			c = (c << 1) | ((i >> j) & 1); //存储最近 x 位的情况
			c &= b;
			if (!c) {
				++tot;   //没有被其它字符串覆盖
			} else {
				int t = c - (c & -c), tmp = getfa(__builtin_ctz(c)); //合并应该相同的字符
				while (t) {
					fa[getfa(__builtin_ctz(t))] = tmp;
					t -= t & -t;
				}
			}
		}
		for (int j = 0; j < x; ++j) tot += (j == fa[j]); //加上不同的数量
		ll tmp = qp(m, tot);
		if (__builtin_parity(i)) { //出现奇数次加,偶数次减,容斥
			ans = (ans + tmp) % mod;
		} else {
			ans = (ans - tmp + mod) % mod;
		}
	}
}
int main() {
	scanf("%d%lld", &n, &m);
	for (int i = 1; i <= n; ++i) sol(i);
	printf("%lld", ans * qp(qp(m, n), mod - 2) % mod); //最后除以总的方案数就是期望
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值