UVa 818:Cutting Chains(暴力)

14 篇文章 0 订阅
5 篇文章 0 订阅

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=842&page=show_problem&problem=759

题意:有n(n \le 15)个圆环,其中有一些已经扣在了一起。现在需要打开尽量少的圆环,使得所有的圆环可以组成一条链(当然,所有打开的圆环最后都要再次闭合)。例如,有5个圆环,1-2,2-3,4-5,则需要打开一个圆环,如圆环4,然后用它穿过圆环3和圆环5后再次闭合圆环4,就可以形成一条链:1-2-3-4-5。(本段摘自《算法竞赛入门经典(第2版)》)

分析:
用二进制枚举断开的圆环数,分析剩下的圆环是否有分支大于2的或者存在环的,如果有则不符合,如果没有,看断开的圆环数+1是否大于等于剩下的圆环组数,如果符合则找到一个解,最后取解的最小值即可。

代码:

#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <cctype>
#include <stack>
#include <set>

using namespace std;

const int maxn = 15 + 5, INF = 10;

int n, x, y, ans, num, C;
int m[maxn][maxn], v[maxn];

bool two(int s)
{
    for (int i = 0; i < n; ++i)
    {
        int cnt = 0;
        for (int j = 0; j < n; ++j)
            if (m[i][j] && !(s & (1 << i)) && !(s & (1 << j)))
            {
                ++cnt;
                if (cnt == 3)
                    return true;
            }
    }
    return false;
}

bool DFS(int x, int f, int s)
{
    v[x] = 1;
    for (int i = 0; i < n; ++i)
        if (m[x][i] && !(s & (1 << i)))
        {
            if (!v[i])
            {
                if (DFS(i, x, s))
                    return true;
            }
            else if (i != f)
                return true;
        }
    return false;
}

bool circle(int s)
{
    memset(v, 0, sizeof(v));
    for (int i = 0; i < n; ++i)
        if (!v[i] && !(s & (1 << i)))
        {
            if (DFS(i, -1, s))
                return true;
            ++num;
        }
    return false;
}

int calc(int s)
{
    int res = 0;
    for (int i = 0; i < n; ++i)
    {
        if (s & 1)
            ++res;
        s >>= 1;
    }
    return res;
}

int main()
{
    while (~scanf("%d", &n), n)
    {
        ans = n;
        memset(m, 0, sizeof(m));
        while (scanf("%d%d", &x, &y), x != -1 && y != -1)
        {
            m[x - 1][y - 1] = 1;
            m[y - 1][x - 1] = 1;
        }
        for (int i = 0; i < (1 << n); ++i)
        {
            num = 0;
            if (two(i) || circle(i))
                continue;
            int tmp = calc(i);
            if (num - 1 <= tmp)
                ans = min(ans, tmp);
        }
        printf("Set %d: Minimum links to open is %d\n", ++C, ans);
    }
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值