Skip to content

Instantly share code, notes, and snippets.

@HarshVardhanKumar
Created January 29, 2018 15:17
Show Gist options
  • Save HarshVardhanKumar/e027443d76b1b0ed81dc1ac04511aa1a to your computer and use it in GitHub Desktop.
Save HarshVardhanKumar/e027443d76b1b0ed81dc1ac04511aa1a to your computer and use it in GitHub Desktop.
Implementation of Prim's Algorithm using STL set in c++
//
// Created by Harsh Vardhan Kumar on 29-01-2018.
//
#include <iostream>
#include <set>
#include <vector>
#define inf 1000000 ;
#define nil -1000000
using namespace std ;
class node {
public:
int parent; int key; int node_val ;
bool operator < (const node & node2) const {
if(this->key < node2.key) return this->key<node2.key ;
else if(this->key == node2.key) return this->node_val<node2.node_val ;
else return this->key < node2.key && this->node_val < node2.node_val ;
//else return this->key < node2.key && this->node_val > node2.node_val ;
}
node(int parentv, int keyv, int node_valv) {
parent = parentv ;
key = keyv ;
node_val = node_valv ;
}
node() {}
};
int main() {
multiset <node> Q ;
vector<vector<pair<int, int> > > adList ;
int no_nodes ; cin>>no_nodes ;
char nod[no_nodes] ;
char nodeval = 'a'-1 ;
for(int i = 0 ; i<no_nodes; i++) {
nodeval++ ;
nod[i] = nodeval ;
}
node nodes[no_nodes] ;
for(int i = 0 ; i<no_nodes; i++) {
vector<pair<int, int> > v ;
adList.push_back(v) ;
node s(-1000000,1000000+i, i) ;
nodes[i] = s ;
}
int w ;
for(int i = 0 ; i<no_nodes; i++) {
for(int j = 0 ; j<no_nodes; j++) {
cin>>w ;
if(w != 100) {
adList[i].emplace_back(make_pair(j, w)) ;
}
}
}
int source; cin>>source ;
nodes[source].key = 0 ;
for(int i = 0 ; i<no_nodes; i++) {
Q.insert(nodes[i]) ;
}
while(!Q.empty()) {
node u = *Q.begin();
//cout<<"node popped is "<<nod[u.node_val]<<endl ;
int u_index = u.node_val ;
// print the queue
nodes[u_index] = u ;
Q.erase(nodes[u_index]) ;
for(pair<int, int> p : adList[u_index]) {
node v = nodes[p.first] ;
if(Q.count(v)>0 && p.second<v.key) {
//cout<<nod[v.node_val]<<" is found with a keyvalue of "<<v.key<<endl ;
Q.erase(v) ;
v.parent = u_index ;
v.key = p.second ;
nodes[v.node_val] = v ;
Q.insert(v) ;
//cout<<"the new key value is "<<v.key<<" and the parent is "<<v.parent<<endl<<endl ;
}
}
}
// now print the values in the nodes array
int weight = 0 ;
for(node n : nodes) {
if(n.parent>=0)
cout<<nod[n.node_val]<<" -- "<<nod[n.parent]<<" "<<endl ;
else cout<<nod[n.node_val]<<" -- "<<"Nil "<<endl;
weight+=n.key ;
}
cout<<"The total weight is "<<weight<<endl ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment