-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDarkRoads.py
42 lines (36 loc) · 1.02 KB
/
DarkRoads.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
import sys
from collections import defaultdict
def find_set(parent, i):
if parent[i] == i:
return i
parent[i] = find_set(parent, parent[i])
return parent[i]
def union_sets(parent, rank, x, y):
xroot = find_set(parent, x)
yroot = find_set(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
while True:
n, m = map(int, sys.stdin.readline().split())
if n == 0 and m == 0:
break
parent = list(range(n))
rank = [0] * n
edges = []
total_cost = 0
for _ in range(m):
x, y, z = map(int, sys.stdin.readline().split())
edges.append((x, y, z))
total_cost += z
edges.sort(key=lambda x: x[2])
min_cost = 0
for u, v, w in edges:
if find_set(parent, u) != find_set(parent, v):
min_cost += w
union_sets(parent, rank, u, v)
print(total_cost - min_cost)