zoukankan      html  css  js  c++  java
  • CCF-CSP题解 201412-4 最优灌溉

    (kruskal),有兴趣(heap\_prim)(stl pq)实现复杂度相同。

    #include <bits/stdc++.h>
    
    using namespace std;
    
    struct tEdge {
        int a, b, c;
        bool operator < (const tEdge &y) const {
            return c < y.c;
        }
    };
    tEdge edge[100005];
    
    int fa[1005];
    
    int father(int x) {return (fa[x] == x) ? x : (fa[x] = father(fa[x]));}
    
    bool combine(int x, int y) {
        int fx = father(x), fy = father(y);
        if (fx != fy) {fa[fx] = fy; return true;}
        return false;
    }
    
    int main() {
        int n, m;
        scanf("%d%d", &n, &m);
    
        for (int i = 0; i < m; ++i) scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].c);
    
        sort(edge, edge + m);
    
        for (int i = 1; i <= n; ++i) fa[i] = i;
    
        int ans = 0;
        for (int i = 0, k = 0; k < n - 1; ++i)
            if (combine(edge[i].a, edge[i].b) == true) {++k; ans += edge[i].c;}
    
        printf("%d", ans);
    
        return 0;
    }
    
    #include <bits/stdc++.h>
    
    using namespace std;
    
    int to[200005], nex[200005], w[200005], head[1005], cnt;
    
    void addEdge(int a, int b, int c) {
        to[cnt] = b; nex[cnt] = head[a]; w[cnt] = c; head[a] = cnt++;
        to[cnt] = a; nex[cnt] = head[b]; w[cnt] = c; head[b] = cnt++;
    }
    
    struct tNode {
        int id, dis;
        tNode(int i, int d) : id(i), dis(d) {}
        bool operator < (const tNode &y) const {
            return dis > y.dis;
        }
    };
    
    int done[1005], dis[1005];
    
    int heap_prim() {
        memset(done, 0, sizeof(done));
        memset(dis, 0x3f, sizeof(dis));
    
        int ans = 0;
        priority_queue<tNode> que;
        dis[1] = 0;
        que.push(tNode(1, 0));
        while (!que.empty()) {
            tNode x = que.top(); que.pop();
            if (done[x.id]) continue;
            ans += x.dis;
            done[x.id] = 1;
            dis[x.id] = 0;
            for (int i = head[x.id]; i != -1; i = nex[i]) {
                int l = to[i];
                if (dis[l] > w[i]) {
                    dis[l] = w[i];
                    que.push(tNode(l, dis[l]));
                }
            }
        }
        return ans;
    }
    
    int main() {
        int n, m;
        scanf("%d%d", &n, &m);
    
        memset(head, -1, sizeof(head));
        cnt = 0;
        for (int _ = 0, a, b, c; _ < m; ++_) {
            scanf("%d%d%d", &a, &b, &c);
            addEdge(a, b, c);
        }
    
        printf("%d", heap_prim());
    
        return 0;
    }
    
  • 相关阅读:
    用orgmode写加密日记
    用emacs加密文件(使用ccrypt)
    C#使用注册表添加删除开机启动项
    WPF中使用第三方字体选择器
    使用rdesktop远程连接Windows桌面
    webbrowser 提交按钮没反应的问题解决办法
    C#中webBrowser加载页面中的不同域的iFrame的源代码的取得
    C# 天涯博客验证码识别(转)
    webbroser 清除COOKIES的解决办法
    使用C#实现ADSL自动拨号
  • 原文地址:https://www.cnblogs.com/acboyty/p/12035612.html
Copyright © 2011-2022 走看看