From e7cf979f7e9b7b85af42ac1396b94ad65763dd0d Mon Sep 17 00:00:00 2001 From: Louie Tan Date: Fri, 20 Oct 2017 05:32:56 +0800 Subject: [PATCH] Union-Find implementation --- utilities/python/union_find.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 utilities/python/union_find.py diff --git a/utilities/python/union_find.py b/utilities/python/union_find.py new file mode 100644 index 00000000..8fe14664 --- /dev/null +++ b/utilities/python/union_find.py @@ -0,0 +1,27 @@ +## Union-Find data structure +## https://en.wikipedia.org/wiki/Disjoint-set_data_structure + +parents = [0, 1, 2, 3, 4, 5, 6] # parent[i] is the parent of i +weights = [1, 1, 1, 1, 1, 1, 1] + +def find_root(parents, p): + '''Average: O(log n)''' + root = p + while parents[root] != root: + root = parents[root] + # Flatten tree + while parents[p] != p: + parents[p], p = root, parents[p] + return root + +def union(parents, p, q): + '''Average: O(log n)''' + p = find_root(parents, p) + q = find_root(parents, q) + # Link the smaller node to the larger node + if weights[p] > weights[q]: + parents[q] = p + weights[p] += weights[q] + else: + parents[p] = q + weights[q] += weights[p]