summaryrefslogtreecommitdiff
path: root/graph/kruskal.cpp
diff options
context:
space:
mode:
authorPaul Jungeblut <paul.jungeblut@gmail.com>2015-12-04 13:20:51 +0100
committerPaul Jungeblut <paul.jungeblut@gmail.com>2015-12-04 13:20:51 +0100
commitc57a6957af68785d8b2d884eeecb4197ff68d0ef (patch)
tree582c5f893f51f8f52ccbfb658e11dda2df87e5d9 /graph/kruskal.cpp
parent7180049c4f1d125384bf4726eedc72f093716d1b (diff)
parent0c9ef64dbe211408f7a4ad26f3d9fab5fa941eba (diff)
merge
Merge branch 'master' of https://github.com/pjungeblut/ChaosKITs
Diffstat (limited to 'graph/kruskal.cpp')
-rw-r--r--graph/kruskal.cpp18
1 files changed, 18 insertions, 0 deletions
diff --git a/graph/kruskal.cpp b/graph/kruskal.cpp
new file mode 100644
index 0000000..4703c45
--- /dev/null
+++ b/graph/kruskal.cpp
@@ -0,0 +1,18 @@
+typedef pair<int,int> ii;
+typedef vector<pair<int,ii>> graph;
+
+//Takes a Graph g (EdgeList!!!) with N nodes and computes the MST and Cost of it. Runtime: O(|E|*log(|E|))
+//Requires UnionFind-Datastructure!!!
+pair<graph,int> buildMST(int N, graph& g) {
+ UnionFind uf(N);
+ graph mst; int mst_cost = 0; int M = g.size();
+ sort(g.begin(),g.end());
+ for(int i = 0; i < M; i++) {
+ int u = g[i].second.first, v = g[i].second.second;
+ if(uf.findSet(u) != uf.findSet(v)) {
+ mst.push_back(g[i]); mst_cost += g[i].first;
+ uf.unionSets(u,v);
+ }
+ }
+ return make_pair(mst,mst_cost);
+} \ No newline at end of file