Problem : https://www.hackerrank.com/challenges/journey-to-the-moon
Logic : Here constrain is we have to make a pair of two scientists which belongs to two different countries. So, we can relate this problem as graph theory and finding all different connected components(scientist who belong to same country) among whole graph. Then, using combinations, we find total pairs. Here, I used adjecency list instead of matrix, because I have faced error of Memory Exceed in python3.
Language : Python3
import queue #outputq=queue.Queue() # bfs search function def bfssearch(snode): q=queue.Queue() totalcv=0 #total vertex in one connected graph q.put(snode) visitednode[snode]=1 totalcv+=1 #outputq.put(snode) while not q.empty(): source = q.get() for j in node: if visitednode[j]!=1: q.put(j) visitednode[j]=1 totalcv+=1 #outputq.put(v) return totalcv # finding total number of connected component def connectednumber(): return outputq.qsize() # unvisited node def unvisitednode(): i=0 check=-1 #all node are visited or not while check==-1 and i<totalnode: if visitednode[i]==0: check=i i+=1 return check #main function start totalnode,edge= list(map(int, input().split(" "))) aa=[] # list to store total vertex in various connected graph # adjecency matrix node = [[]for y in range(totalnode)] #mark visited # 1 if node is visited 0 if not visited . initially set all zero visitednode = [0 for x in range(totalnode)] # adding edge in matrix. for i in range(0,edge): xx,yy = list(map(int, input().split(" "))) node[xx].append(yy) node[yy].append(xx) #starting bfs search with 0. for h in range(0,totalnode): if visitednode[h]==0: aa.append(bfssearch(h)) #combination calculation total = (sum(aa)*(sum(aa)-1))//2 for j in aa: total-=(j*(j-1))//2 print(total)