Created
November 15, 2015 07:37
-
-
Save yask123/934b5332fc93e1e77d12 to your computer and use it in GitHub Desktop.
Kruskap MSP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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