【题解】CF906C:Party

原题传送门
状压
01状态中所有1表示互相认识
s t a i sta_i stai表示初始 i i i的交际圈,如果 i i i在状态 J J J中,可以直接把 s t a i sta_i stai的状态直接并入 J J J,表示选择 i i i,把他认识的人都互相认识一遍

然后记录路径, i d J id_J idJ表示该状态是通过选择 i d J id_J idJ这个人来的, p r e J pre_J preJ表示上个状态

Code:

#include <bits/stdc++.h>
#define maxn 5000010
#define maxm 25
using namespace std;
const int inf = 1e9;
int power[maxm], n, m, sta[maxm], dp[maxn], id[maxn], pre[maxn];

inline int read(){
    
    
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

int main(){
    
    
	n = read(), m = read();
	if (m == n * (n - 1) / 2) return puts("0"), 0;
	power[0] = 1;
	for (int i = 1; i <= n; ++i) power[i] = power[i - 1] << 1;
	for (int i = 1; i <= n; ++i) sta[i] = power[i - 1];
	for (int i = 1; i <= m; ++i){
    
    
		int x = read(), y = read();
		sta[x] |= power[y - 1], sta[y] |= power[x - 1];
	}
	for (int i = 1; i <= power[n] - 1; ++i) dp[i] = inf;
	for (int i = 1; i <= n; ++i) dp[sta[i]] = 1, id[sta[i]] = i;
	for (int i = 0; i < power[n]; ++i){
    
    
		if (dp[i] == inf) continue;
		for (int j = 1; j <= n; ++j)
			if ((i & power[j - 1]) && (dp[i | sta[j]] > dp[i] + 1)){
    
    
				dp[i | sta[j]] = dp[i] + 1,
				id[i | sta[j]] = j,
				pre[i | sta[j]] = i;
			}
	}
	n = power[n] - 1;
	printf("%d\n", dp[n]);
	while (n) printf("%d ", id[n]), n = pre[n];
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ModestCoder_/article/details/108630861