题目链接:
https://vjudge.net/problem/UVA-818
题意:
选几个圆环去open。然后该圆环和其他就断开了。然后用这些open的圆环去连接剩下的圆环【最后打开的会合上】,看能不能连成一串。。求最少的open个数。
题解:
n为15.利用位运算去枚举哪几个圆环要open。然后判断剩下圆环有没有与超过2个圆环的连接或者形成环,如果没有,在判断剩下的链个数有没有超过open个数-1.如果条件都符合,那么保留下最小最为答案。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
int n,vis[20],g[20][20],cnt;
bool two(int s){
for(int i=0; i<n; i++){
if(s & (1<<i)) continue;
int cnt = 0;
for(int j=0; j<n; j++){
if(s & (1<<j)) continue;
if(g[i][j] && i!=j) cnt++;
}
if(cnt > 2) return true;
}
return false;
}
bool dfs(int s,int now,int fa){
vis[now] = 1;
for(int i=0; i<n; i++){
if(!g[now][i] || s&(1<<i) || i==fa) continue;
if(vis[i]) return true;
if(dfs(s,i,now)) return true;
}
return false;
}
bool circle(int s){
for(int i=0; i<n; i++){
if(s & (1<<i)) continue;
if(vis[i]) continue;
cnt++;
if(dfs(s,i,-1)) return true;
}
return false;
}
int cal(int x){
return x==0 ? 0 : cal(x/2)+(x%2);
}
int main(){
int cas = 1;
while(scanf("%d",&n) && n){
MS(g);
int u,v;
while(scanf("%d%d",&u,&v)){
if(u==-1 && v==-1) break;
g[u-1][v-1] = g[v-1][u-1] = 1;
}
int s = (1<<n);
int ans = INF;
for(int i=0; i<s; i++){
MS(vis); cnt=0; // cnt 表示 如果剩下的环中,没有连成圈的, 那有几条链
if(two(i) || circle(i)) continue;
if(cal(i) >= cnt-1) // 如果拆下来的环 大于链数-1 才能连成一条链
ans = min(ans,cal(i));
}
printf("Set %d: Minimum links to open is %d\n",cas++,ans);
}
return 0;
}