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,astronaut):# Initialize disjoint set (union-find) structuresroot=list(range(n))rank=[0]*ndeffind_root(a):ifroot[a]!=a:root[a]=find_root(root[a])#Pathcompressionreturnroot[a]defunion(a,b):i,j=find_root(a),find_root(b)ifi!=j:ifrank[i]>rank[j]:root[j]=ielifrank[i]<rank[j]:root[i]=jelse:root[j]=irank[i]+=1# Union all astronaut pairsfora,binastronaut:union(a,b)# Count the size of each connected componentcomponent_sizes=list(Counter(find_root(i)foriinrange(n)).values())# Calculate the number of valid pairstotal_pairs=0sum_sizes=0forsizeincomponent_sizes:total_pairs+=sum_sizes*size#Pairsbetweencurrentandpreviouscomponentssum_sizes+=size#Updatethecumulativesizesumreturntotal_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 →