An intuitive Prim algorithm impl.
#include <vector>#include<iostream>#include<queue>#include<unordered_map>#include<unordered_set>using namespacestd;structedge{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()(ConstEdge &e1,ConstEdge &E2) { returne1.d >e2.d; }};intMain () {LongN, M; CIN >> N >>m; //From -to-and (length, id)unordered_map<unsigned, unordered_map<unsigned, unsigned>>G; for(inti =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 Inxpriority_queue<edge, Vector<edge>, edge>Q; for(Auto &Kv:g[s]) {Q.push (Edge (S, Kv.first, Kv.second)); } pickedset.insert (s); unsignedLong LongRET =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;}
Hackerrank "Prim ' (MST): Special subtree"