Skip to content
Related Articles

Related Articles

Improve Article

Finding Astronauts from different countries

  • Difficulty Level : Hard
  • Last Updated : 14 Sep, 2021

Given a positive integer N denoting the number of astronauts(labelled from 0 from (N – 1))and a matrix mat[][] containing the pairs of astronauts that are from the same country, the task is to count the number of ways to choose two astronauts from different countries.

Examples:

Input: N = 6, mat[][] = {{0, 1}, {0, 2}, {2, 5}}
Output: 9
Explanation:
Astronauts with ID {0, 1, 2, 5} belong to first country, astronaut with ID {3} belongs to second country and astronaut with ID {4} belongs to third country. The number of ways to choose two astronauts from different countries is:

  1. Choose 1 astronaut from country 1 and 1 astronaut from country 2, then the total number of ways is 4*1 = 4.
  2. Choose 1 astronaut from country 1 and 1 astronaut from country 3, then the total number of ways is 4*1 = 4.
  3. Choose 1 astronaut from country 2 and 1 astronaut from country 3, then the total number of ways is 1*1 = 1.

Therefore, the total number of ways is 4 + 4 + 1 = 9. 

Input: N = 5, mat[][] = {{0, 1}, {2, 3}, {0, 4}}
Output: 6



Approach: The given problem can be solved by modeling this problem as a graph in which astronauts represent the vertices of the graph and the given pairs represent the edges in the graph. After constructing the graph, the idea is to calculate the number of ways to select 2 astronauts from different countries. Follow the steps to solve the problem:

  • Create a list of lists, adj[][] to store the adjacency list of the graph.
  • Traverse the given array arr[] using the variable i and append arr[i][1] to adj[arr[i][0]] and also append arr[i][0] to adj[arr[i][1]] for the undirected edge.
  • Now find the size of each connected component of the graph by performing the Depth First Search, using the approach discussed in this article, and store all the sizes of connected components be stored in an array say v[].
  • Initialize an integer variable, say ans as the total number of ways to choose 2 astronauts from N astronauts i.e., N*(N – 1)/2.
  • Traverse the array v[] and subtract v[i]*(v[i] – 1)/2 from the variable ans to exclude all possible pairs among each connected components.
  • After completing the above steps, print the value of ans as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to perform the DFS Traversal
// to find the count of connected
// components
void dfs(int v, vector<vector<int> >& adj,
         vector<bool>& visited, int& num)
{
    // Marking vertex visited
    visited[v] = true;
    num++;
 
    // DFS call to neighbour vertices
    for (int i = 0; i < adj[v].size(); i++) {
 
        // If the current node is not
        // visited, then recursively
        // call DFS
        if (!visited[adj[v][i]]) {
            dfs(adj[v][i], adj,
                visited, num);
        }
    }
}
 
// Function to find the number of ways
// to choose two astronauts from the
// different countries
void numberOfPairs(
    int N, vector<vector<int> > arr)
{
    // Stores the Adjacency list
    vector<vector<int> > adj(N);
 
    // Constructing the graph
    for (vector<int>& i : arr) {
        adj[i[0]].push_back(i[1]);
        adj[i[1]].push_back(i[0]);
    }
 
    // Stores the visited vertices
    vector<bool> visited(N);
 
    // Stores the size of every
    // connected components
    vector<int> v;
 
    int num = 0;
    for (int i = 0; i < N; i++) {
 
        if (!visited[i]) {
 
            // DFS call to the graph
            dfs(i, adj, visited, num);
 
            // Store size of every
            // connected component
            v.push_back(num);
            num = 0;
        }
    }
 
    // Stores the total number of
    // ways to count the pairs
    int ans = N * (N - 1) / 2;
 
    // Traverse the array
    for (int i : v) {
        ans -= (i * (i - 1) / 2);
    }
 
    // Print the value of ans
    cout << ans;
}
 
// Driver Code
int main()
{
    int N = 6;
    vector<vector<int> > arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } };
    numberOfPairs(N, arr);
 
    return 0;
}

Javascript




<script>
    // Javascript program for the above approach 
     
    // Function to perform the DFS Traversal
    // to find the count of connected
    // components
     
    let adj;
    let visited;
    let num;
     
    function dfs(v)
    {
        // Marking vertex visited
        visited[v] = true;
        num++;
 
        // DFS call to neighbour vertices
        for (let i = 0; i < adj[v].length; i++) {
 
            // If the current node is not
            // visited, then recursively
            // call DFS
            if (!visited[adj[v][i]]) {
                dfs(adj[v][i]);
            }
        }
    }
 
    // Function to find the number of ways
    // to choose two astronauts from the
    // different countries
    function numberOfPairs(N, arr)
    {
        // Stores the Adjacency list
        adj = [];
        for(let i = 0; i < N; i++)
        {
            adj.push([]);
        }
 
        // Constructing the graph
        for (let i = 0; i < arr.length; i++) {
            adj[arr[i][0]].push(arr[i][1]);
            adj[arr[i][1]].push(arr[i][0]);
        }
 
        // Stores the visited vertices
        visited = new Array(N);
        visited.fill(false);
 
        // Stores the size of every
        // connected components
        let v = [];
 
        num = 0;
        for (let i = 0; i < N; i++) {
 
            if (!visited[i]) {
 
                // DFS call to the graph
                dfs(i);
 
                // Store size of every
                // connected component
                v.push(num);
                num = 0;
            }
        }
 
        // Stores the total number of
        // ways to count the pairs
        let ans = N * (N - 1) / 2;
 
        // Traverse the array
        for (let i = 0; i < v.length; i++) {
            ans -= (v[i] * (v[i] - 1) / 2);
        }
 
        // Print the value of ans
        document.write(ans);
    }
     
    let N = 6;
    let arr = [ [ 0, 1 ], [ 0, 2 ], [ 2, 5 ] ];
    numberOfPairs(N, arr);
 
// This code is contributed by rameshtravel07.
</script>
Output: 
9

 

Time Complexity: O(N + E), where N is the number of vertices and E is the number of edges.
Auxiliary Space: O(N + E)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :