题意
有n(n≤15)个圆环,其中有一些已经扣在了一起。现在需要打开尽量少的圆环,使得所有圆环可组成一条链(所有打开的圆环最后都要再次闭合)。例如,有5个圆环,1-2,2-3,4-5,则需要打开一个圆环,如圆环4,然后用它穿过圆环3和圆环5后再次闭合圆环4,就可以形成一条链:1-2-3-4-5
题解
由于n比较小,可以枚举所有的破环情况,破环后再分别判断是否形成多叉或环的情况即可,枚举时用二进制枚举
#include <bits/stdc++.h>
#include <unordered_set>
#include <unordered_map>
#define _for(i, a, b) for(int i = a; i < b; ++i)
#define _rep(i, a, b) for(int i = a; i <= b; ++i)
#define closeIO ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define debug cout << "******************" << endl
#define FREE freopen("in.txt", "r", stdin)
#define FREO freopen("out.txt", "w", stdout)
#define ls l, m, rt << 1
#define rs m + 1, r, rt << 1 | 1
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> pii;
typedef long double LD;
const int MAXN = 1e5 + 10;
const int MOD = 998244353;
const double eps = 1e-6;
int n, cs = 1, cnt;
bool G[20][20], vis[20];
bool input() {
scanf("%d", &n);
if (n == 0) return false;
memset(G, false, sizeof(G));
int u, v;
while (scanf("%d%d", &u, &v)) {
if (u == -1) return true;
G[u][v] = G[v][u] = true;
}
}
bool dfs(int s, int u, int fa) {
if (vis[u]) return true;
vis[u] = true;
_rep(v, 1, n) {
if (v == fa || v == u || !G[u][v]) continue;
if ((1 << (v - 1)) & s) continue;
if (dfs(s, v, u)) return true;
}
return false;
}
bool judge(int s) {
_rep(i, 1, n) {
if ((1 << (i - 1)) & s) continue;
int res = 0;
_rep(j, 1, n) {
if (((1 << (j - 1)) & s) || i == j) continue;
if (G[i][j]) ++res;
}
if (res > 2) return false;
}
cnt = 0;
memset(vis, false, sizeof(vis));
_rep(i, 1, n) {
if (((1 << (i - 1)) & s) || vis[i]) continue;
++cnt;
if (dfs(s, i, -1)) return false;
}
return true;
}
int num(int x) { return x ? num(x / 2) + (x & 1) : 0; }
int solve() {
int ans = n - 1;
_for(i, 0, 1 << n) {
if (judge(i)) {
if (num(i) >= cnt - 1)
ans = min(ans, num(i));
}
}
return ans;
}
int main() {
while (input()) printf("Set %d: Minimum links to open is %d\n", cs++, solve());
return 0;
}