loj #2540. 「PKUWC2018」随机算法 状压DP

题目:点击打开链接

题解:点击打开链接

关键点:转化为状压DP算方案数,考虑优化,使得当前状态只需记录是否被点考虑过,

而未被考虑过的点一定不和最大独立集联通。概率=合法方案/总方案

            因为每个子集中独立集也一定最大(不与外界联通),所以可以不用记当前点数。

    只需在更新时保证最大即可

#include
using namespace std;
#define maxn 1200000

typedef long long ll;
const ll p = 998244353;
int next[30];
int n,m,mx[maxn],sz[maxn],N;
ll f[maxn],fac[50],inv[50];

ll power(ll x,int y){
	ll res = 1;
	while ( y ){
		if ( y & 1 ) res = res * x % p;
		x = x * x % p;
		y >>= 1;
	}
	return res;
}
void init(){
	fac[0] = 1 , inv[0] = 1;
	for (int i = 1 ; i <= 30 ; i++) fac[i] = fac[i - 1] * i % p;
	inv[30] = power(fac[30],p - 2);
	for (int i = 29 ; i >= 1 ; i--) inv[i] = inv[i + 1] * (i + 1) % p;
	for (int i = 0 ; i < N ; i++){
		for (int j = 0 ; j < n ; j++) if ( i & (1 << j) ) sz[i]++;
	}
}
inline ll A(int n,int m){
	if ( n == 0 ) return 1;
	return fac[n] * inv[n - m] % p;
}
int main(){
	freopen("input.txt","r",stdin);
	scanf("%d %d",&n,&m);
	for (int i = 1 ; i <= m ; i++){
		int x,y;
		scanf("%d %d",&x,&y) , x-- , y--;
		next[x] |= 1 << y , next[y] |= 1 << x;
	}
	for (int i = 0 ; i < n ; i++) next[i] |= 1 << i;
	N = (1 << n) , init() , f[0] = 1;
	for (int i = 0 ; i < N - 1 ; i++) if ( f[i] ){
		for (int j = 0 ; j < n ; j++){
			if ( !(i & (1 << j)) ){
				int cur = i | next[j];
				if ( mx[cur] < mx[i] + 1 ) f[cur] = 0 , mx[cur] = mx[i] + 1;
				if ( mx[cur] == mx[i] + 1 ){
					f[cur] = (f[cur] + f[i] * A(n - sz[i] - 1,sz[next[j]] - sz[i & next[j]] - 1)) % p;
				}	
			}
		}
	}
	cout<

你可能感兴趣的:(ACM,DP)