We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
this one is bit easy if you use DFS and simple Formula for possible pairs for a given node i.e n(n-1)//2
importosdefdfs(u,visited,adj):res=[]stack=[u]visited[u]=Truewhilestack:node=stack.pop()res.append(node)foriinadj[node]:ifvisited[i]==False:stack.append(i)visited[i]=Truereturnlen(res)defjourneyToMoon(n,astronaut):adjList={v:[]forvinrange(n)}ans=[]forx,yinastronaut:adjList[x].append(y)adjList[y].append(x)visited=[False]*nforuinrange(n):ifvisited[u]==False:a=dfs(u,visited,adjList)ans.append(a)# Possible pairs for give Number of nodestotal=n*(n-1)//2foriinans:total-=i*(i-1)//2returntotalif__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')first_multiple_input=input().rstrip().split()n=int(first_multiple_input[0])p=int(first_multiple_input[1])astronaut=[]for_inrange(p):astronaut.append(list(map(int,input().rstrip().split())))result=journeyToMoon(n,astronaut)fptr.write(str(result)+'\n')fptr.close()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Journey to the Moon
You are viewing a single comment's thread. Return to all comments →
this one is bit easy if you use DFS and simple Formula for possible pairs for a given node i.e n(n-1)//2