Skip to content

Commit ff72bbd

Browse files
authored
Create 3613. Minimize Maximum Component Cost.py
1 parent 3977b20 commit ff72bbd

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#
2+
3+
'''
4+
1. 아이디어 :
5+
아무것도 연결하지 않은채로 시작.
6+
edge를 가장 작은것부터 연결한다.
7+
k개의 components일때까지 연결한다. (자연스럽게 가장 큰것들은 0이 됨)
8+
9+
2. 시간복잡도 :
10+
O(n)
11+
12+
3. 자료구조/알고리즘 :
13+
union-find
14+
15+
'''
16+
class Solution:
17+
def minCost(self, n: int, edges: List[List[int]], k: int) -> int:
18+
#union find
19+
# edges.sort(key=lambda x: x[2])
20+
# for i in range(k-1):
21+
# edges.pop()
22+
# return edges[-1][2] if edges else 0
23+
24+
def find(x):
25+
if par[x] != x:
26+
par[x] = find(par[x])
27+
return par[x]
28+
29+
def union(a, b):
30+
a = find(a)
31+
b = find(b)
32+
33+
if a == b:
34+
return False
35+
36+
if size[a] < size[b]:
37+
a, b = b, a
38+
39+
par[b] = a
40+
size[a] += size[b]
41+
return True
42+
43+
par = [i for i in range(n)]
44+
size = [1] * n
45+
46+
edges.sort(key=lambda x: x[2])
47+
48+
components = n
49+
ans = 0
50+
51+
for u, v, w in edges:
52+
if components<=k:
53+
break
54+
55+
if union(u, v):
56+
components -= 1
57+
ans = w
58+
59+
return ans if components <= k else -1

0 commit comments

Comments
 (0)