Can anyone point out what could be wrong in this simple implementation of Prim’s algorithm?
void prims (unordered_map<int,set<pair<int,int>>> g, int n) {
vector<int> mstSet; // in MST
vector<bool> visited(n,false);
unordered_map<int,int> V; // vertex key array
int u = 0;
V[u] = 0;
mstSet.push_back(u);
visited[u]=true;
while(mstSet.size()!=n) {
for(auto it:g[u]) {
// w < v.key then v.key = w
if(it.ff<V[it.ss]) V[it.ss]=it.ff;
}
int mi = inf;
for(auto it:V) {
if(it.second<mi && !visited[it.first]) {
u = it.first;
mi=it.second;
}
}
mstSet.push_back(u);
visited[u] = true;
}
for(auto i:mstSet) cout << i << " ";
}
Here’s the main method.
int main () {
unordered_map<int,set<pair<int,int>>> e;
struct construct con;
con.make_weighted(e,4,0,1);
con.make_weighted(e,8,0,7);
con.make_weighted(e,11,1,7);
con.make_weighted(e,8,1,2);
con.make_weighted(e,7,7,8);
con.make_weighted(e,1,7,6);
con.make_weighted(e,2,2,8);
con.make_weighted(e,6,8,6);
con.make_weighted(e,2,6,5);
con.make_weighted(e,7,2,3);
con.make_weighted(e,4,2,5);
con.make_weighted(e,14,3,5);
con.make_weighted(e,9,3,4);
con.make_weighted(e,10,5,4);
prims(e,9);
return 0;
}
And here’s the “struct construct”.
struct construct {
void make_weighted (unordered_map<int,set<pair<int,int>>>& g, int c, int u, int v) {
g[u].insert({c,v});
g[v].insert({c,u});
}
};
, the pair holds the (value, node index ) info