Finding Astronauts from different countries
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:
- Choose 1 astronaut from country 1 and 1 astronaut from country 2, then the total number of ways is 4*1 = 4.
- Choose 1 astronaut from country 1 and 1 astronaut from country 3, then the total number of ways is 4*1 = 4.
- 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++
#include <bits/stdc++.h>
using namespace std;
void dfs( int v, vector<vector< int > >& adj,
vector< bool >& visited, int & num)
{
visited[v] = true ;
num++;
for ( int i = 0; i < adj[v].size(); i++) {
if (!visited[adj[v][i]]) {
dfs(adj[v][i], adj,
visited, num);
}
}
}
void numberOfPairs(
int N, vector<vector< int > > arr)
{
vector<vector< int > > adj(N);
for (vector< int >& i : arr) {
adj[i[0]].push_back(i[1]);
adj[i[1]].push_back(i[0]);
}
vector< bool > visited(N);
vector< int > v;
int num = 0;
for ( int i = 0; i < N; i++) {
if (!visited[i]) {
dfs(i, adj, visited, num);
v.push_back(num);
num = 0;
}
}
int ans = N * (N - 1) / 2;
for ( int i : v) {
ans -= (i * (i - 1) / 2);
}
cout << ans;
}
int main()
{
int N = 6;
vector<vector< int > > arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } };
numberOfPairs(N, arr);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static Vector<Vector<Integer>> adj;
static boolean [] visited;
static int num;
static void dfs( int v)
{
visited[v] = true ;
num++;
for ( int i = 0 ; i < adj.get(v).size(); i++) {
if (!visited[adj.get(v).get(i)]) {
dfs(adj.get(v).get(i));
}
}
}
static void numberOfPairs( int N, int [][] arr)
{
adj = new Vector<Vector<Integer>>();
for ( int i = 0 ; i < N; i++)
{
adj.add( new Vector<Integer>());
}
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 ]);
}
visited = new boolean [N];
Arrays.fill(visited, false );
Vector<Integer> v = new Vector<Integer>();
num = 0 ;
for ( int i = 0 ; i < N; i++) {
if (!visited[i]) {
dfs(i);
v.add(num);
num = 0 ;
}
}
int ans = N * (N - 1 ) / 2 + 1 ;
for ( int i = 0 ; i < v.size(); i++) {
ans -= (v.get(i) * (v.get(i) - 1 ) / 2 ) + 1 ;
}
System.out.print(ans);
}
public static void main(String[] args) {
int N = 6 ;
int [][] arr = { { 0 , 1 }, { 0 , 2 }, { 2 , 5 } };
numberOfPairs(N, arr);
}
}
|
Python3
adj = []
visited = []
num = 0
def dfs(v):
global adj, visited, num
visited[v] = True
num + = 1
for i in range ( len (adj[v])):
if ( not visited[adj[v][i]]):
dfs(adj[v][i])
def numberOfPairs(N, arr):
global adj, visited, num
adj = []
for i in range (N):
adj.append([])
for i in range ( len (arr)):
adj[arr[i][ 0 ]].append(arr[i][ 1 ])
adj[arr[i][ 1 ]].append(arr[i][ 0 ])
visited = [ False ] * (N)
v = []
num = 0
for i in range (N):
if ( not visited[i]):
dfs(i)
v.append(num)
num = 0
ans = N * int ((N - 1 ) / 2 )
for i in range ( len (v)):
ans - = (v[i] * int ((v[i] - 1 ) / 2 ))
ans + = 1
print (ans)
N = 6
arr = [ [ 0 , 1 ], [ 0 , 2 ], [ 2 , 5 ] ]
numberOfPairs(N, arr)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static List<List< int >> adj;
static bool [] visited;
static int num;
static void dfs( int v)
{
visited[v] = true ;
num++;
for ( int i = 0; i < adj[v].Count; i++) {
if (!visited[adj[v][i]]) {
dfs(adj[v][i]);
}
}
}
static void numberOfPairs( int N, int [,] arr)
{
adj = new List<List< int >>();
for ( int i = 0; i < N; i++)
{
adj.Add( new List< int >());
}
for ( int i = 0; i < 2; i++) {
adj[arr[i,0]].Add(arr[i,1]);
adj[arr[i,1]].Add(arr[i,0]);
}
visited = new bool [N];
Array.Fill(visited, false );
List< int > v = new List< int >();
num = 0;
for ( int i = 0; i < N; i++) {
if (!visited[i]) {
dfs(i);
v.Add(num);
num = 0;
}
}
int ans = N * (N - 1) / 2 + 1;
for ( int i = 0; i < v.Count; i++) {
ans -= (v[i] * (v[i] - 1) / 2) +1;
}
Console.Write(ans);
}
static void Main() {
int N = 6;
int [,] arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } };
numberOfPairs(N, arr);
}
}
|
Javascript
<script>
let adj;
let visited;
let num;
function dfs(v)
{
visited[v] = true ;
num++;
for (let i = 0; i < adj[v].length; i++) {
if (!visited[adj[v][i]]) {
dfs(adj[v][i]);
}
}
}
function numberOfPairs(N, arr)
{
adj = [];
for (let i = 0; i < N; i++)
{
adj.push([]);
}
for (let i = 0; i < arr.length; i++) {
adj[arr[i][0]].push(arr[i][1]);
adj[arr[i][1]].push(arr[i][0]);
}
visited = new Array(N);
visited.fill( false );
let v = [];
num = 0;
for (let i = 0; i < N; i++) {
if (!visited[i]) {
dfs(i);
v.push(num);
num = 0;
}
}
let ans = N * (N - 1) / 2;
for (let i = 0; i < v.length; i++) {
ans -= (v[i] * (v[i] - 1) / 2);
}
document.write(ans);
}
let N = 6;
let arr = [ [ 0, 1 ], [ 0, 2 ], [ 2, 5 ] ];
numberOfPairs(N, arr);
</script>
|
Time Complexity: O(N + E), where N is the number of vertices and E is the number of edges.
Auxiliary Space: O(N + E)
Last Updated :
23 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...