From d46fc541a941f5026ce713d381e637d535785672 Mon Sep 17 00:00:00 2001 From: HawkEye201 Date: Thu, 15 Oct 2020 03:41:54 +0530 Subject: [PATCH] Added Kruskal ALgorithm --- C++/graph/Kruskal_Algorithm.cpp | 80 +++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 C++/graph/Kruskal_Algorithm.cpp diff --git a/C++/graph/Kruskal_Algorithm.cpp b/C++/graph/Kruskal_Algorithm.cpp new file mode 100644 index 0000000..8d5c82c --- /dev/null +++ b/C++/graph/Kruskal_Algorithm.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include +using std::vector; +//create a point class +struct point{ + int x; int y; int parent; int rank; + point(int a, int b, int c, int d):x(a), y(b), parent(c), rank(d){} +}; +//create a edge class +struct Edge{ + int indexa, indexb; + double length; + Edge(int a, int b, double c):indexa(a), indexb(b), length(c){} +}; +//formula for finding distance between two coordinates +double distance(int x1, int y1, int x2, int y2){ + return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)); +} +//custom sorting edges according to edges length +struct sort_edges{ + inline bool operator()(const Edge& struct1, const Edge& struct2){ + return (struct1.length < struct2.length); + } +}; +//finds parent of each vertices +int find(int i, vector &points){ + int x=i; + while(i != points[i].parent) + i=points[i].parent; + points[x].parent=i; + return i; +} +//joins two vertices +void Union(int a, int b, vector &points){ + if(points[a].rank < points[b].rank) + points[a].parent = b; + else { + points[b].parent = a; + if(points[a].rank == points[b].rank){ + points[a].rank++; + } + } +} +//takes two arrays having x and y coordinates respectively and returns minimium distance between them +double minimum_distance(vector x, vector y) { + double result = 0.0; + vector points; + for(int i=0; i edges; + for(int i=0; i> n; + vector x(n), y(n);//taking input x and y having x and y coordinate of points + for (size_t i = 0; i < n; i++) { + std::cin >> x[i] >> y[i]; + } + std::cout << std::setprecision(10) << minimum_distance(x, y) << std::endl; +}