zoukankan      html  css  js  c++  java
  • 最小生成树 || HDU 1301 Jungle Roads

    裸的最小生成树

    输入很蓝瘦

    **并查集

    int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
    

    找到x在并查集里的根结点,如果两个端点在同一个集合内,find之后两个值就相等了

    每次找到权值最小的端点不在同一集合的边 把两个集合合并

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    int fa[33];
    struct node
    {
        int s, e, d;
    }l[111];
    bool cmp(node x, node y)
    {
        if(x.d != y.d) return x.d < y.d;
    }
    int find(int x)
    {
        return x == fa[x] ? x : fa[x] = find(fa[x]);
    }
    int main()
    {
        while(1)
        {
            int n, i, j, x, val, sum = 0, cnt = 0;//cnt是边数
            char c;
            scanf("%d", &n);
            if(n == 0) break;
            for(i = 0; i < n - 1; i++)
            {
                scanf(" %c", &c);
                int s = c - 'A' + 1;
                scanf("%d", &x);
                for(j = 0; j < x; j++)
                {
                    scanf(" %c %d", &c, &val);
                    int e = c - 'A' + 1;
                    l[cnt++] = (node){s, e, val};
                }
            }
            sort(l, l + cnt, cmp);
            for(int i = 1; i <= n; i++)
                fa[i] = i;
            for(int i = 0; i < cnt; i++)
            {
                int fs = find(l[i].s), fe = find(l[i].e);
                if(fs == fe) continue;
                sum += l[i].d;
                fa[fs] = fe;
            }
            printf("%d
    ", sum);
        }
        return 0;
    }
  • 相关阅读:
    dracut-initqueue timeout
    Request.Url
    ipv4 ipv6数据库存储
    DataRow To DataTable
    AS ShortCut
    linq on 多链接条件
    SQL逻辑查询语句执行顺序
    ckeditor 使用几点
    SqlDataAdapter 更新插入 与 InsertBulkCopy
    HTTP协议改HTTPS
  • 原文地址:https://www.cnblogs.com/pinkglightning/p/8428656.html
Copyright © 2011-2022 走看看