hdu 3367 Pseudoforest

每个连通分量最多只有一个环,求怎么连接使费用最大

按费用从大到小排序,一条一条加边,连接一个集合内两个点的时候,判断这个集合之前有没有成环,连接两个集合的时候,判断两个集合的状态,如果都没有,则合并后也没有环,如果有一个有环,合并有也有环,如果两个都有环,则不能合并。

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int father[100010], g[100010], ff[100010], bb[100010];
struct abc{ int start, end, cost; }node[100010];
bool cmp(const abc&a, const abc&b){ return a.cost > b.cost; }
int find(int x)
{
    if (x != father[x]) father[x] = find(father[x]);
    return father[x];
}
int main()
{
    int n, m, i, j, u, v, c, t;
    while (~scanf("%d%d", &n, &m))
    {
        if (n == 0 && m == 0) break;
        int tot = 0;
        memset(ff, 0, sizeof(ff));
        memset(bb, 0, sizeof(bb));
        for (i = 0; i <= n; i++) father[i] = i;
        for (i = 1; i <= m; i++)
        {
            scanf("%d%d%d", &u, &v, &c);
            node[tot].start = u;
            node[tot].end = v;
            node[tot].cost = c;
            tot++;
        }
        sort(node, node + tot, cmp);
        int ans = 0;
        for (i = 0; i < tot; i++)
        {
            int x = find(node[i].start);
            int y = find(node[i].end);
            if (x == y)
            {
                if (bb[x] == 0)
                {
                    bb[x] = 1;
                    ans = ans + node[i].cost;
                }
            }
            else if (x != y)
            {
                if (bb[x] == 0&&bb[y]==0)
                {
                    father[y] = x;
                    ans = ans + node[i].cost;
                }
                else if (bb[x] == 0&&bb[y]==1)
                {
                    bb[x] = 1;
                    father[y] = x;
                    ans = ans + node[i].cost;
                }
                else if (bb[x] == 1 && bb[y] == 0)
                {
                    bb[y] = 1;
                    father[x] = y;
                    ans = ans + node[i].cost;
                }
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/zufezzt/p/4484672.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值