bzoj2560 串珠子 状压DP

题目传送门

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

题解

大概是这类关于无向图的联通性计数的套路了。

一开始我想的是这样的,考虑容斥,那么就是令 \(dp[i][S]\) 表示我钦定了 \(i\) 个连通块必须断开其余随意的方案数,然后 DP 完以后容斥加起来就可以了。

但是这样是 \(O(3^nn)\) 的,好像没有前途。

然后想到这个关于无向连通图计数的套路:用对于每一个状态,用总的方案数减去不连通的方案数。但是为了不连通的方案数不重不漏,我们可以在包含某一个钦定的点的连通块处统计。

\(dp[S]\) 表示 \(S\) 集合中的点联通的方案数,\(f[S]\)\(S\) 集合中的点的无向图的个数。\(f\) 显然很好求。

dp 转移就是枚举包含钦定的点的集合,这个集合必须联通。不妨设这个钦定的点为 \(p\)

\[dp[S] = f[S] - \sum_{sta \subseteq S \& p \in sta} dp[sta] \cdot f[S - sta] \]

然后就没有了,时间复杂度为 \(O(3^nn + 2^nn^2)\)

#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;
}

#define lowbit(x) ((x) & -(x))

const int N = 16 + 7;
const int M = (1 << 16) + 7;
const int P = 1e9 + 7;

int n, S;
int a[N][N];
int dp[M], f[M];

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() {
	S = (1 << n) - 1;
	for (int s = 0; s <= S; ++s) {
		int &ans = f[s] = 1;
		for (int i = 1; i <= n; ++i) if ((s >> (i - 1)) & 1)
			for (int j = i + 1; j <= n; ++j) if ((s >> (j - 1)) & 1)
				ans = (ll)ans * (a[i][j] + 1) % P;
	}
}

inline void DP() {
	for (int s = 1; s <= S; ++s) {
		dp[s] = f[s];
		int tp = lowbit(s);
		for (int sta = s; sta; sta = (sta - 1) & s)
			if ((sta & tp) && s != sta) sadd(dp[s], P - (ll)f[s ^ sta] * dp[sta] % P);
	}
}

inline void work() {
	ycl();
	DP();
	printf("%d\n", dp[S]);
}

inline void init() {
	read(n);
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= n; ++j) read(a[i][j]);
}

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