Skip to content

Commit 975623c

Browse files
authored
Create optimize-water-distribution-in-a-village.py
1 parent d5abd64 commit 975623c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Time: O(nlogn)
2+
# Space: O(n)
3+
4+
class UnionFind(object):
5+
def __init__(self, n):
6+
self.set = range(n)
7+
self.count = n
8+
9+
def find_set(self, x):
10+
if self.set[x] != x:
11+
self.set[x] = self.find_set(self.set[x]) # path compression.
12+
return self.set[x]
13+
14+
def union_set(self, x, y):
15+
x_root, y_root = map(self.find_set, (x, y))
16+
if x_root == y_root:
17+
return False
18+
self.set[max(x_root, y_root)] = min(x_root, y_root)
19+
self.count -= 1
20+
return True
21+
22+
23+
class Solution(object):
24+
def minCostToSupplyWater(self, n, wells, pipes):
25+
"""
26+
:type n: int
27+
:type wells: List[int]
28+
:type pipes: List[List[int]]
29+
:rtype: int
30+
"""
31+
w = [[c, 0, i] for i, c in enumerate(wells, 1)]
32+
p = [[c, i, j] for i, j, c in pipes]
33+
result = 0
34+
union_find = UnionFind(n+1)
35+
for c, x, y in sorted(w+p):
36+
if not union_find.union_set(x, y):
37+
continue
38+
result += c
39+
if union_find.count == 1:
40+
break
41+
return result

0 commit comments

Comments
 (0)