BZOJ2839 集合计数 二项式反演

题目传送门

https://lydsy.com/JudgeOnline/problem.php?id=2839

题解

二项式反演板子题。

类似于一般的容斥,我们发现恰好 \(k\) 个不怎么好求,但是至少 \(k\) 个还是很好求的。

考虑固定 \(k\) 个数必须存在,然后剩下的 \(n-k\) 个数的集合的子集中随意选择(不能不选),所以至少 \(k\) 个的方案就是 \(\binom nk (2^{2^{n-k}}-1)\)

\(f(k)\) 表示钦定了至少 \(k\) 个的方案,\(g(k)\) 表示恰好 \(k\) 个的方案。可以发现很显然 \(f(k) = \sum\limits_{i=k}^n \binom ik g(i)\)

所以就可以直接二项式反演了。


下面是代码,\(2^{2^k}\) 可以 \(O(n)\) 预处理,因此总的时间复杂度为 \(O(n)\)

#include<bits/stdc++.h>

#define fec(i, x, y) (int i = head[x], y = g[i].to; i; i = g[i].ne, y = g[i].to)
#define dbg(...) fprintf(stderr, __VA_ARGS__)
#define File(x) freopen(#x".in", "r", stdin), freopen(#x".out", "w", stdout)
#define fi first
#define se second
#define pb push_back

template<typename A, typename B> inline char smax(A &a, const B &b) {return a < b ? a = b , 1 : 0;}
template<typename A, typename B> inline char smin(A &a, const B &b) {return b < a ? a = b , 1 : 0;}

typedef long long ll; typedef unsigned long long ull; typedef std::pair<int, int> pii;

template<typename I>
inline void read(I &x) {
	int f = 0, c;
	while (!isdigit(c = getchar())) c == '-' ? f = 1 : 0;
	x = c & 15;
	while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + (c & 15);
	f ? x = -x : 0;
}

const int N = 1000000 + 7;
const int P = 1e9 + 7;

int n, k;
int f[N], pw[N];
int fac[N], inv[N], ifac[N];

inline int smod(int x) { return x >= P ? x - P : x; }
inline void sadd(int &x, const int &y) { x += y; x >= P ? x -= P : x; }
inline int fpow(int x, int y) {
	int ans = 1;
	for (; y; y >>= 1, x = (ll)x * x % P) if (y & 1) ans = (ll)ans * x % P;
	return ans;
}

inline void ycl() {
	fac[0] = 1; for (int i = 1; i <= n; ++i) fac[i] = (ll)fac[i - 1] * i % P;
	inv[1] = 1; for (int i = 2; i <= n; ++i) inv[i] = (ll)(P - P / i) * inv[P % i] % P;
	ifac[0] = 1; for (int i = 1; i <= n; ++i) ifac[i] = (ll)ifac[i - 1] * inv[i] % P;
	pw[0] = 2; for (int i =  1; i <= n; ++i) pw[i] = (ll)pw[i - 1] * pw[i - 1] % P;
}
inline int C(int x, int y) {
	if (x < y) return 0;
	return (ll)fac[x] * ifac[y] % P * ifac[x - y] % P;
}

inline void work() {
	ycl();
	for (int i = 0; i <= n; ++i) f[i] = (ll)C(n, i) * (pw[n - i] + P - 1) % P;
	int ans = 0;
	for (int i = k; i <= n; ++i)
		if ((i - k) & 1) sadd(ans, P - (ll)C(i, k) * f[i] % P);
		else sadd(ans, (ll)C(i, k) * f[i] % P);
	printf("%d\n", ans);
}

inline void init() {
	read(n), read(k);
}

int main() {
#ifdef hzhkk
	freopen("hkk.in", "r", stdin);
#endif
	init();
	work();
	fclose(stdin), fclose(stdout);
	return 0;
}
posted @ 2019-09-10 23:12  hankeke303  阅读(211)  评论(0编辑  收藏  举报