zoukankan      html  css  js  c++  java
  • HDU1879 继续畅通工程

    问题链接:HDU1879 继续畅通工程

    问题描述:参见上述链接

    问题分析:这是一个最小生成树的为问题,解决的算法有Kruskal(克鲁斯卡尔)算法和Prim(普里姆) 算法。

    程序说明:本程序使用Kruskal算法实现。有关最小生成树的问题,使用克鲁斯卡尔算法更具有优势,只需要对所有的边进行排序后处理一遍即可。程序中使用了并查集,用来判定加入一条边后会不会产生循环。程序中,图采用边列表的方式存储,按边的权从小到大顺序放在优先队列中,省去了排序。

    AC的C++语言程序如下:

    /* HDU1879 继续畅通工程 */
    
    #include <iostream>
    #include <queue>
    #include <cstdio>
    
    using namespace std;
    
    const int MAXN = 100;
    
    // 并查集
    int v[MAXN+1];
    class UF {
    public:
        UF() {}
    
        // 压缩
        int Find(int x) {
            if(x == v[x])
                return x;
            else
                return v[x] = Find(v[x]);
        }
    
        bool Union(int x, int y) {
            x = Find(x);
            y = Find(y);
            if(x == y)
                return false;
            else {
                v[x] = y;
                return true;
            }
        }
    
        void reset(int n) {
            for(int i=0; i<=n; i++)
                v[i] = i;
        }
    };
    
    struct edge {
        int src, dest, cost;
        bool operator < (const edge& n) const {
            return cost > n.cost;
        }
    };
    
    int main()
    {
        int n, ecount, status;
        UF uf;
        edge e;
    
        while(scanf("%d", &n) != EOF && n) {
            priority_queue<edge> q;     // 优先队列,用于存储边列表
    
            uf.reset(n);
    
            ecount = n * (n - 1) / 2;
            while(ecount--) {
                scanf("%d%d%d%d", &e.src, &e.dest, &e.cost, &status);
    
                if(status == 1)
                    uf.Union(e.src, e.dest);
                else
                    q.push(e);
    
    
            }
    
            // Kruskal算法:获得最小生成树
            int ans=0, count=0;
            while(!q.empty()) {
                e = q.top();
                q.pop();
    
                if(uf.Union(e.src, e.dest)) {
                    count++;
                    ans += e.cost;
                }
    
                if(count == n - 1)
                    break;
            }
    
            // 输出结果
            printf("%d
    ", ans);
        }
    
        return 0;
    }



  • 相关阅读:
    高级映射之事务
    配置tomcat-users.xml文件
    动态SQL之标签
    性能测试
    Service
    添加 aar 或 jar 包依赖 的方式
    安卓设备 以太网代理 问题排查
    剑指offer:面试题15、链表中倒数第 K 个结点
    剑指offer:面试题14、调整数组顺序使奇数位于偶数前面
    剑指offer:面试题13、在O(1)时间删除链表结点
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564093.html
Copyright © 2011-2022 走看看