From e07e0cb38bf3ea7f7301641fe877fe473248fabb Mon Sep 17 00:00:00 2001 From: Thanapat Katapornsiri Date: Fri, 27 Oct 2017 14:16:26 +0700 Subject: [PATCH 1/2] add minimum spanning tree kruskal --- Graphs/minimum_spanning_tree_kruskal.py | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Graphs/minimum_spanning_tree_kruskal.py diff --git a/Graphs/minimum_spanning_tree_kruskal.py b/Graphs/minimum_spanning_tree_kruskal.py new file mode 100644 index 000000000..d329774c8 --- /dev/null +++ b/Graphs/minimum_spanning_tree_kruskal.py @@ -0,0 +1,31 @@ +num_nodes, num_edges = list(map(int,input().split())) + +edges = [] + +for i in range(num_edges): + node1, node2, cost = list(map(int,input().split())) + edges.append((i,node1,node2,cost)) + +edges = sorted(edges, key=lambda edge: edge[3]) + +parent = [i for i in range(num_nodes)] + +def find_parent(i): + if(i != parent[i]): + parent[i] = find_parent(parent[i]) + return parent[i] + +minimum_spanning_tree_cost = 0 +minimum_spanning_tree = [] + +for edge in edges: + parent_a = find_parent(edge[1]) + parent_b = find_parent(edge[2]) + if(parent_a != parent_b): + minimum_spanning_tree_cost += edge[3] + minimum_spanning_tree.append(edge) + parent[parent_a] = parent_b + +print(minimum_spanning_tree_cost) +for edge in minimum_spanning_tree: + print(edge) \ No newline at end of file From 6393251803b6562d9b2ea98cf1385d1dbb0207d9 Mon Sep 17 00:00:00 2001 From: Thanapat Katapornsiri Date: Fri, 27 Oct 2017 14:34:44 +0700 Subject: [PATCH 2/2] add newline at the end --- Graphs/minimum_spanning_tree_kruskal.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graphs/minimum_spanning_tree_kruskal.py b/Graphs/minimum_spanning_tree_kruskal.py index d329774c8..d26eb70b2 100644 --- a/Graphs/minimum_spanning_tree_kruskal.py +++ b/Graphs/minimum_spanning_tree_kruskal.py @@ -28,4 +28,4 @@ for edge in edges: print(minimum_spanning_tree_cost) for edge in minimum_spanning_tree: - print(edge) \ No newline at end of file + print(edge)