-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogrammers_greedy_5.py
55 lines (42 loc) · 1.31 KB
/
programmers_greedy_5.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def solution(n, costs):
answer = 0
costs.sort(key = lambda x : (x[2], x[0]))
connect = []
for i in range(n):
connect.append(i)
def findParent(land, connect) :
if (connect[land] == land) :
return connect[land]
else :
return findParent(connect[land], connect)
for i in range(0, len(costs)) :
first = findParent(costs[i][0], connect)
second = findParent(costs[i][1], connect)
if(first != second) :
connect[second] = first
answer+= costs[i][2]
print(connect)
return answer
def solution2(n, costs):
answer = 0
costs.sort(key = lambda x : (x[2], x[0]))
connect = []
for i in range(n):
connect.append(i)
def findParent(land, connect) :
if (connect[land] == land) :
return connect[land]
else :
return findParent(connect[land], connect)
for i in range(0, len(costs)) :
first = findParent(costs[i][0], connect)
second = findParent(costs[i][1], connect)
if(first != second) :
connect[costs[i][1]] = first
answer+= costs[i][2]
print(connect)
return answer
n = 5
costs = [[0,1,1],[3,4,1],[1,2,2],[2,3,4]]
print(solution(n, costs))
print(solution2(n, costs))