zoukankan      html  css  js  c++  java
  • HackerRank "Prim's (MST) : Special Subtree"

    An intuitive Prim algorithm impl.

    #include <vector>
    #include <iostream>
    #include <queue>
    #include <unordered_map>
    #include <unordered_set>
    using namespace std;
    
    struct Edge
    {
        Edge() :s(0), t(0), d(0) {}
        Edge(unsigned rs, unsigned rt, unsigned rd) :
            s(rs), t(rt), d(rd) {}
    
        unsigned s;
        unsigned t;
        unsigned d;
    
        bool operator()(const Edge &e1, const Edge &e2)
        {
            return e1.d > e2.d;
        }
    };
    
    int main()
    {
        long n, m; cin >> n >> m;
        //    from -> to -> (length, id)
        unordered_map<unsigned, unordered_map<unsigned, unsigned>> g;
        for (int i = 0; i < m; i++)
        {
            unsigned a, b, d; cin >> a >> b >> d;
            g[a][b] = g[b][a] = d;
        }
        unsigned s; cin >> s;
    
        unordered_set<unsigned> pickedSet; // linked node inx
    
        priority_queue<Edge, vector<Edge>, Edge> q;
        for (auto &kv : g[s])
        {
            q.push(Edge(s, kv.first, kv.second));
        }
        pickedSet.insert(s);
    
        unsigned long long ret = 0;
        while (!q.empty())
        {
            Edge picked = q.top();
            q.pop();
            if (pickedSet.count(picked.t)) continue;
    
            pickedSet.insert(picked.t);
    
            // add new choices
            for (auto &kv : g[picked.t])
            {
                q.push(Edge(picked.t, kv.first, kv.second));
            }
    
            ret += picked.d;
        }
        cout << ret << endl;
        return 0;
    }
  • 相关阅读:
    【转】acm小技巧
    poj-1703-Find them, Catch them
    poj-1611-The Suspects
    poj-2236-Wireless Network
    hdu-4496-D-City
    hdu-1213-How Many Tables
    hdu-1856-More is better
    gcd和ex_gcd
    递归趣文
    算法实质【Matrix67】
  • 原文地址:https://www.cnblogs.com/tonix/p/5480555.html
Copyright © 2011-2022 走看看