# Finding Astronauts from different countries

• Difficulty Level : Hard
• Last Updated : 23 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] to adj[arr[i]] and also append arr[i] to adj[arr[i]] 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 ``using` `namespace` `std;` `// Function to perform the DFS Traversal``// to find the count of connected``// components``void` `dfs(``int` `v, vector >& 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 > arr)``{``    ``// Stores the Adjacency list``    ``vector > adj(N);` `    ``// Constructing the graph``    ``for` `(vector<``int``>& i : arr) {``        ``adj[i].push_back(i);``        ``adj[i].push_back(i);``    ``}` `    ``// 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 > arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } };``    ``numberOfPairs(N, arr);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;``public` `class` `GFG``{``    ``// Function to perform the DFS Traversal``    ``// to find the count of connected``    ``// components``    ``static` `Vector> adj;``    ``static` `boolean``[] visited;``    ``static` `int` `num;``    ` `    ``// Function to perform the DFS Traversal``    ``// to find the count of connected``    ``// components``    ``static` `void` `dfs(``int` `v)``    ``{``      ` `        ``// Marking vertex visited``        ``visited[v] = ``true``;``        ``num++;``  ` `        ``// DFS call to neighbour vertices``        ``for` `(``int` `i = ``0``; i < adj.get(v).size(); i++) {``  ` `            ``// If the current node is not``            ``// visited, then recursively``            ``// call DFS``            ``if` `(!visited[adj.get(v).get(i)]) {``                ``dfs(adj.get(v).get(i));``            ``}``        ``}``    ``}``  ` `    ``// Function to find the number of ways``    ``// to choose two astronauts from the``    ``// different countries``    ``static` `void` `numberOfPairs(``int` `N, ``int``[][] arr)``    ``{``        ``// Stores the Adjacency list``        ``adj = ``new` `Vector>();``        ``for``(``int` `i = ``0``; i < N; i++)``        ``{``            ``adj.add(``new` `Vector());``        ``}``  ` `        ``// Constructing the graph``        ``for` `(``int` `i = ``0``; i < ``2``; i++) {``            ``adj.get(arr[i][``0``]).add(arr[i][``1``]);``            ``adj.get(arr[i][``1``]).add(arr[i][``0``]);``        ``}``  ` `        ``// Stores the visited vertices``        ``visited = ``new` `boolean``[N];``        ``Arrays.fill(visited, ``false``);``  ` `        ``// Stores the size of every``        ``// connected components``        ``Vector v = ``new` `Vector();``  ` `        ``num = ``0``;``        ``for` `(``int` `i = ``0``; i < N; i++) {``  ` `            ``if` `(!visited[i]) {``  ` `                ``// DFS call to the graph``                ``dfs(i);``  ` `                ``// Store size of every``                ``// connected component``                ``v.add(num);``                ``num = ``0``;``            ``}``        ``}``  ` `        ``// Stores the total number of``        ``// ways to count the pairs``        ``int` `ans = N * (N - ``1``) / ``2` `+ ``1``;``  ` `        ``// Traverse the array``        ``for` `(``int` `i = ``0``; i < v.size(); i++) {``            ``ans -= (v.get(i) * (v.get(i) - ``1``) / ``2``) +``1``;``        ``}``  ` `        ``// Print the value of ans``        ``System.out.print(ans);``    ``}``    ` `    ``public` `static` `void` `main(String[] args) {``        ``int` `N = ``6``;``        ``int``[][] arr = { { ``0``, ``1` `}, { ``0``, ``2` `}, { ``2``, ``5` `} };``        ``numberOfPairs(N, arr);``    ``}``}` `// This code is contributed by suresh07`

## Python3

 `# Python3 program for the above approach` `# Function to perform the DFS Traversal``# to find the count of connected``# components``adj ``=` `[]``visited ``=` `[]``num ``=` `0`` ` `def` `dfs(v):``    ``global` `adj, visited, num``    ` `    ``# Marking vertex visited``    ``visited[v] ``=` `True``    ``num``+``=``1` `    ``# DFS call to neighbour vertices``    ``for` `i ``in` `range``(``len``(adj[v])):``      ` `        ``# If the current node is not``        ``# visited, then recursively``        ``# call DFS``        ``if` `(``not` `visited[adj[v][i]]):``            ``dfs(adj[v][i])` `# Function to find the number of ways``# to choose two astronauts from the``# different countries``def` `numberOfPairs(N, arr):``    ``global` `adj, visited, num``    ``# Stores the Adjacency list``    ``adj ``=` `[]``    ``for` `i ``in` `range``(N):``        ``adj.append([])` `    ``# Constructing the graph``    ``for` `i ``in` `range``(``len``(arr)):``        ``adj[arr[i][``0``]].append(arr[i][``1``])``        ``adj[arr[i][``1``]].append(arr[i][``0``])` `    ``# Stores the visited vertices``    ``visited ``=` `[``False``]``*``(N)` `    ``# Stores the size of every``    ``# connected components``    ``v ``=` `[]` `    ``num ``=` `0``    ``for` `i ``in` `range``(N):``        ``if` `(``not` `visited[i]):``            ``# DFS call to the graph``            ``dfs(i)` `            ``# Store size of every``            ``# connected component``            ``v.append(num)``            ``num ``=` `0` `    ``# Stores the total number of``    ``# ways to count the pairs``    ``ans ``=` `N ``*` `int``((N ``-` `1``) ``/` `2``)` `    ``# Traverse the array``    ``for` `i ``in` `range``(``len``(v)):``        ``ans ``-``=` `(v[i] ``*` `int``((v[i] ``-` `1``) ``/` `2``))``    ``ans``+``=``1` `    ``# Print the value of ans``    ``print``(ans)` `N ``=` `6``arr ``=` `[ [ ``0``, ``1` `], [ ``0``, ``2` `], [ ``2``, ``5` `] ]``numberOfPairs(N, arr)` `# This code is contributed by mukesh07.`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;``class` `GFG {``    ` `    ``// Function to perform the DFS Traversal``    ``// to find the count of connected``    ``// components``    ``static` `List> adj;``    ``static` `bool``[] visited;``    ``static` `int` `num;``    ` `    ``// Function to perform the DFS Traversal``    ``// to find the count of connected``    ``// components``    ``static` `void` `dfs(``int` `v)``    ``{``        ``// Marking vertex visited``        ``visited[v] = ``true``;``        ``num++;`` ` `        ``// DFS call to neighbour vertices``        ``for` `(``int` `i = 0; i < adj[v].Count; 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``    ``static` `void` `numberOfPairs(``int` `N, ``int``[,] arr)``    ``{``        ``// Stores the Adjacency list``        ``adj = ``new` `List>();``        ``for``(``int` `i = 0; i < N; i++)``        ``{``            ``adj.Add(``new` `List<``int``>());``        ``}`` ` `        ``// Constructing the graph``        ``for` `(``int` `i = 0; i < 2; i++) {``            ``adj[arr[i,0]].Add(arr[i,1]);``            ``adj[arr[i,1]].Add(arr[i,0]);``        ``}`` ` `        ``// Stores the visited vertices``        ``visited = ``new` `bool``[N];``        ``Array.Fill(visited, ``false``);`` ` `        ``// Stores the size of every``        ``// connected components``        ``List<``int``> v = ``new` `List<``int``>();`` ` `        ``num = 0;``        ``for` `(``int` `i = 0; i < N; i++) {`` ` `            ``if` `(!visited[i]) {`` ` `                ``// DFS call to the graph``                ``dfs(i);`` ` `                ``// Store size of every``                ``// connected component``                ``v.Add(num);``                ``num = 0;``            ``}``        ``}`` ` `        ``// Stores the total number of``        ``// ways to count the pairs``        ``int` `ans = N * (N - 1) / 2 + 1;`` ` `        ``// Traverse the array``        ``for` `(``int` `i = 0; i < v.Count; i++) {``            ``ans -= (v[i] * (v[i] - 1) / 2) +1;``        ``}`` ` `        ``// Print the value of ans``        ``Console.Write(ans);``    ``}``    ` `  ``static` `void` `Main() {``    ``int` `N = 6;``    ``int``[,] arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } };``    ``numberOfPairs(N, arr);``  ``}``}` `// This code is contributed by divyesh072019.`

## Javascript

 ``

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)

My Personal Notes arrow_drop_up