From f174ae4adef9718f95c0c7c4d6361653876bd1ad Mon Sep 17 00:00:00 2001 From: RaghavKaushal03 Date: Sun, 9 Oct 2022 16:18:10 +0530 Subject: [PATCH] kruskal algo added --- Kruskal.cpp | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Kruskal.cpp diff --git a/Kruskal.cpp b/Kruskal.cpp new file mode 100644 index 0000000..e4d4092 --- /dev/null +++ b/Kruskal.cpp @@ -0,0 +1,84 @@ +#include +#include +#include +using namespace std; + +#define edge pair + +class Graph { + private: + vector > G; // graph + vector > T; // mst + int *parent; + int V; // number of vertices/nodes in graph + public: + Graph(int V); + void AddWeightedEdge(int u, int v, int w); + int find_set(int i); + void union_set(int u, int v); + void kruskal(); + void print(); +}; +Graph::Graph(int V) { + parent = new int[V]; + for (int i = 0; i < V; i++) + parent[i] = i; + + G.clear(); + T.clear(); +} +void Graph::AddWeightedEdge(int u, int v, int w) { + G.push_back(make_pair(w, edge(u, v))); +} +int Graph::find_set(int i) { + if (i == parent[i]) + return i; + else + return find_set(parent[i]); +} + +void Graph::union_set(int u, int v) { + parent[u] = parent[v]; +} +void Graph::kruskal() { + int i, uRep, vRep; + sort(G.begin(), G.end()); // increasing weight + for (i = 0; i < G.size(); i++) { + uRep = find_set(G[i].second.first); + vRep = find_set(G[i].second.second); + if (uRep != vRep) { + T.push_back(G[i]); // add to tree + union_set(uRep, vRep); + } + } +} +void Graph::print() { + cout << "Edge :" + << " Weight" << endl; + for (int i = 0; i < T.size(); i++) { + cout << T[i].second.first << " - " << T[i].second.second << " : " + << T[i].first; + cout << endl; + } +} +int main() { + Graph g(6); + g.AddWeightedEdge(0, 1, 4); + g.AddWeightedEdge(0, 2, 4); + g.AddWeightedEdge(1, 2, 2); + g.AddWeightedEdge(1, 0, 4); + g.AddWeightedEdge(2, 0, 4); + g.AddWeightedEdge(2, 1, 2); + g.AddWeightedEdge(2, 3, 3); + g.AddWeightedEdge(2, 5, 2); + g.AddWeightedEdge(2, 4, 4); + g.AddWeightedEdge(3, 2, 3); + g.AddWeightedEdge(3, 4, 3); + g.AddWeightedEdge(4, 2, 4); + g.AddWeightedEdge(4, 3, 3); + g.AddWeightedEdge(5, 2, 2); + g.AddWeightedEdge(5, 4, 3); + g.kruskal(); + g.print(); + return 0; +} \ No newline at end of file