https://vjudge.net/contest/220824#problem/D
STL容器Bitset用法https://www.cnblogs.com/Ash-ly/p/5890024.html
fill函数,fill_n函数用法https://blog.csdn.net/monkeyduck/article/details/44536371
感谢博主
暴力搜索,利用位运算简化了代码,逻辑也变得清晰了许多
#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<queue>
#include<bitset>
#pragma warning(disable:4996)
using namespace std;
#define _for(i,a,b) for(int i=(a);i<(b);++i)
#define _rep(i,a,b) for(int i=(a);i<=(b)++i)
const int MAXN = 15;
int G[MAXN][MAXN]; //邻接矩阵存图
int n; //节点个数
int C[MAXN]; //dfs判圈
bool dfs(int u, int f, bitset<MAXN> bitop) //dfs判重,注意写法
{
if (C[u] == -1) return false;
if (C[u] == 1) return true;
if (bitop.test(u)) { C[u] = 1; return true; }
C[u] = -1;
_for(v, 0, n) if (G[u][v] && v != f && !dfs(v, u, bitop)) return false;
C[u] = 1;
return true;
}
bool deg(int i, bitset<MAXN> bitop) //计算节点i的度数
{
int cnt = 0;
if (bitop.test(i)) return true;
_for(j, 0, n) {
if (G[i][j] && !bitop.test(j)) cnt++;
}
return cnt <= 2;
}
int solve()
{
int ans = n;
bitset<MAXN> bitop;
for (int k = 0; k < (1 << n); k++) {
bitop.reset();
for (int i = 0; i < n; i++) if ((1 << i)&k) bitop.set(i);
int value = true;
_for(i, 0, n) if (!bitop.test(i) && !deg(i, bitop)) { value = false; break; }
if (!value) continue;
fill_n(C, MAXN, 0);
int ti = 0;
_for(i, 0, n) {
if (bitop.test(i)) continue;
if(!C[i]) ti++;
if(!dfs(i, -1, bitop)) { value = false; break; }
}
if (!value) continue;
int kc = bitop.count();
if (ti <= kc + 1) {
ans = min(kc, ans);
}
}
return ans;
}
int main()
{
for (int kcase = 1; scanf("%d", &n) == 1&&n; kcase++)
{
memset(G, 0, sizeof(G));
int u, v;
while (scanf("%d%d", &u, &v) == 2 && u!=-1) {
G[u-1][v-1] = G[v-1][u-1] = 1;
}
printf("Set %d: Minimum links to open is %d\n", kcase, solve());
}
}