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.
First I'm constructing a graph.If two astronauts u,v belongs to same country then I'm adding an edge in the graph between u and v as well as v and u ( it's an undirected graph ). I'm using adjacency list representation.
So now,we have n vertices(astronauts) so there can be n*(n-1)/2 pairs of astronauts at max. So initial result=n*(n-1)/2
Next I'm doing DFS to find all components and no of vertices of each component. Lets say this is m. So we can have m*(m-1)/2 pairs from this component.So m*(m-1)/2 astronauts can't be chosen (because they belongs to same country ). Hence I'm subtracting this count from result.
That's it
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 →
Nice problem
*Idea behind solution *