Anyone who solved this please help me with the code. Is my I/O operations correct? I used the same approach for a similar problem in hackerrank and it passed all the test cases even with 10000 edges.
import heapq
from collections import defaultdict
def Find(Parent,U):
if Parent[U]==-1:
return U
return Find(Parent,Parent[U])
def Union(Parent,U,V):
Parent[Find(Parent,U)]=Find(Parent,V)
def hasCycle(Graph,Parent):
for i in Graph:
for node in Graph[i]:
if Find(Parent,node)==Find(Parent,i):
return True
else:
Union(Parent,node,i)
return False
def Kruskal(Graph,N):
Parent={i:-1 for i in range(1,N+1)}
MST=0
edges=0
while edges<N-1:
W,U,V=heapq.heappop(Graph)
if Find(Parent,U)!=Find(Parent,V):
edges+=1
MST+=W
Union(Parent,U,V)
return MST
try:
for i in range(int(input())):
Graph=[]
temp_graph=defaultdict(list)
empty=input()
N=int(input())
for U in range(1,N+1):
city=input()
for niegh in range(int(input())):
V,W=map(int,input().split())
if V>U:
heapq.heappush(Graph,(W,U,V))
print(Kruskal(Graph,N))
except:
flag=False
created
last reply
- 2
replies
- 867
views
- 2
users
- 1
link