Skip to content

Instantly share code, notes, and snippets.

@yask123
Created November 15, 2015 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yask123/5b558c9e788b4544fe71 to your computer and use it in GitHub Desktop.
Save yask123/5b558c9e788b4544fe71 to your computer and use it in GitHub Desktop.
Kruskal algo MSP
#include <iostream>
#include <vector>
#include <map>
using namespace std;
struct Edge{
char vertex1;
char vertex2;
int weight;
Edge() : vertex1(v1), vertex2(v2), weight(w) {}
};
struct Graph{
vector <char> vertices;
vector <Edge> edges;
};
map <char,char> PARENT;
map <char,char> RANK;
char Find(char item){
if(PARENT[item] == item)
return item;
else
return Find(PARENT[item]);
}
void MST(Graph& g){
vector<Edge> res;
for(auto c : g.vertices){
PARENT[c]=c;
RANK[c]=0;
}
sort(g.edges.begin(), g.edges.end(),[](Edge x, Edge y) {return x.weight < y.weight; });
for (Edge e() : g.edges){
char root1 = Find(e.vertex1);
char root2 = Find(e.vertex2);
if (root1 != root2){
res.push_back(e);
if(RANK[root1] > RANK[root2]){
PARENT[root2] = root1;
RANK[root1]+=1;
}
else{
PARENT[root1]=root2;
RANK[root2]+=1;
}
}
}
for (Edge e: res) {
cout << e.vertex1 << "-- " << e.vertex2 << " -- " << e.weight;
}
}
int main()
{
char t[]={'a','b','c','d','e','f'};
Graph g;
g.vertices = vector <char> (t,t+sizeof(t)/sizeof(t[0]));
g.edges.push_back(Edge());
g.edges.push_back(Edge());
g.edges.push_back(Edge());
g.edges.push_back(Edge());
g.edges.push_back(Edge());
g.edges.push_back(Edge());
g.edges.push_back(Edge());
g.edges.push_back(Edge());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment