1 / 3
Aug 2020

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

    Aug '20
  • last reply

    Aug '20
  • 2

    replies

  • 867

    views

  • 2

    users

  • 1

    link

I wonder what could be going wrong here that you’re ignoring. When I remove these, the code gives NZEC

It may only be the the input isn’t formatted exactly as it should be. Although if that was the case, there would usually be some complaints in the comments.

You could try making how you read the the input a little more flexible so that it won’t fail if the format isn’t exactly as expected.

BLINNET3