Repository navigation
Journey to the Moon
Moustafa Attia edited this page Dec 6, 2017
·
1 revision
This wiki to show my solution for HackerRank problem Journey to the Moon
- this is connected component graph problem
- we can consider each astronauts as separate node
- connect each astronauts (node) with another astronauts who are from same country
- do this connection vice versa, i.e. astronauts A and B from same country and also astronauts B and A. (un-directed graph)
- after that each connected component represent separate country
- now we need to compute number of node for each connected component, and store it in array
- now apply this pattern to find number of ways using the previous array:
- suppose we have four sizes (A,B,C and D)
- now the number of ways will be using this formula(the order doesn’t matter) : A*B + A*C + A*D + B*C + B*D + C*D
- which is equal to: A*B + (A+B)*C + (A+B+C)*D
def getRoots(aNeigh):
# get connected components
# https://stackoverflow.com/questions/10301000/python-connected-components
def findRoot(aNode,aRoot):
while aNode != aRoot[aNode][0]:
aNode = aRoot[aNode][0]
return (aNode,aRoot[aNode][1])
myRoot = {}
for myNode in aNeigh.keys():
myRoot[myNode] = (myNode,0)
for myI in aNeigh:
for myJ in aNeigh[myI]:
(myRoot_myI,myDepthMyI) = findRoot(myI,myRoot)
(myRoot_myJ,myDepthMyJ) = findRoot(myJ,myRoot)
if myRoot_myI != myRoot_myJ:
myMin = myRoot_myI
myMax = myRoot_myJ
if myDepthMyI > myDepthMyJ:
myMin = myRoot_myJ
myMax = myRoot_myI
myRoot[myMax] = (myMax,max(myRoot[myMin][1]+1,myRoot[myMax][1]))
myRoot[myMin] = (myRoot[myMax][0],-1)
myToRet = {}
for myI in aNeigh:
if myRoot[myI][0] == myI:
myToRet[myI] = []
for myI in aNeigh:
myToRet[findRoot(myI,myRoot)[0]].append(myI)
return myToRet
n,p = [int(x) for x in input().split(' ')]
graph = {}
for _ in range(p):
a,b = [str(x) for x in input().split(' ')]
# connect both nodes with each other
if a not in graph:
s = set()
s.add(b)
graph[a] = s
else :
graph[a].add(b)
if b not in graph:
s = set()
s.add(a)
graph[b] = s
else :
graph[b].add(a)
sizes = []
sum_sizes = 0
# array of countries sizes
for x in getRoots(graph).values() :
sizes.append(len(x))
sum_sizes += len(x)
# to handle case when single nodes exist (connected component with 1 node)
if sum_sizes < n :
for i in range(n-sum_sizes) :
sizes.append(1)
sm = 0
result = 0
# apply the pattern to find total number of ways
for size in sizes :
result += sm*size
sm += size
print(result)