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.
fromcollectionsimportCounterdefjourneyToMoon(n:int,astronaut:list[tuple[int,int]])->int:parent=list(range(n))deffind(i):ifparent[i]==i:returniparent[i]=find(parent[i])returnparent[i]defunion(i,j):root_i=find(i)root_j=find(j)ifroot_i!=root_j:parent[root_i]=root_jfora,binastronaut:union(a,b)country_sizes=Counter(find(i)foriinrange(n)).values()total_pairs=(n*(n-1))// 2 same_country_pairs=sum(size*(size-1)// 2 for size in country_sizes)returntotal_pairs-same_country_pairs
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 →
Python 3