-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ-43
More file actions
29 lines (29 loc) · 707 Bytes
/
Q-43
File metadata and controls
29 lines (29 loc) · 707 Bytes
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
import heapq
n,m=map(int,input().split())
graph=[[0,1,7],[0,3,5],[1,2,8],[1,3,9],[1,4,7],[2,4,5],[3,4,15],[3,5,6],[4,5,8],[4,6,9],[5,6,11]]
q=[]
for k in graph:
x,y,z=k
heapq.heappush(q,(z,x,y))
parent=[0]*n
for i in range(n):
parent[i]=i
def find_parent(parent,x):
if parent[x]!=x:
parent[x]=find_parent(parent,parent[x])
return parent[x]
def union_parent(parent,a,b):
a=find_parent(parent,a)
b=find_parent(parent,b)
if a<b:
parent[b]=a
else:
parent[a]=b
result=sum=0
while q:
dist,x,y=heapq.heappop(q)
sum+=dist
if find_parent(parent,x)!=find_parent(parent,y):
union_parent(parent,x,y)
result+=dist
print(sum-result)