Journey to the Moon


Problem Statement :


The member states of the UN are planning to send  people to the moon. They want them to be from different countries. You will be given a list of pairs of astronaut ID's. Each pair is made of astronauts from the same country. Determine how many pairs of astronauts from different countries they can choose from.


Function Description

Complete the journeyToMoon function in the editor below.

journeyToMoon has the following parameter(s):

int n: the number of astronauts
int astronaut[p][2]: each element  is a  element array that represents the ID's of two astronauts from the same country


Returns

- int: the number of valid pairs

Input Format

The first line contains two integers  and , the number of astronauts and the number of pairs.
Each of the next  lines contains  space-separated integers denoting astronaut ID's of two who share the same nationality.



Solution :


                            Solution in C :

in  C :




#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int FindP(int *P, int x) {
    if(P[x] != x) {
        P[x] = FindP(P, P[x]);
    }
    return P[x];
}

int MergeS(int *P, int *R, int *C, int A, int B) {
    if(R[A] < R[B]) {
        P[A] = B;
        C[B] += C[A];
    } else if(R[A] > R[B]) {
        P[B] = A;
        C[A] += C[B];
    } else {
        P[B] = A;
        R[A] += 1;
        C[A] += C[B];
    }
}



int main() {
    int R[100000], P[100000], C[100000], i, N, I, A, B, UC;
    int M[100000], S[100000];
    unsigned long long result;
    scanf("%d%d", &N, &I);
    for(i=0;i<N;i++) {
        P[i] = i;
        C[i] = 1;
        R[i] = 0;
    }
    for(i=0;i<I;i++) {
        scanf("%d%d", &A, &B);
        A = FindP(P, A);
        B = FindP(P, B);
        if(A != B)
            MergeS(P, R, C, A, B);
    }
    UC = 0;
    for(i=0;i<N;i++) {
        if(P[i] == i) {
            M[UC++] = C[i];
        }
    }
    S[0] = M[0];
    for(i=1;i<UC;i++) {
        S[i] = S[i-1] + M[i];
    }
    result = 0;
    for(i=0;i<UC-1;i++) {
        A = M[i];
        B = S[UC-1] - S[i];
        result += A*B;
    }
    printf("%llu", result);
    return 0;
}
                        

                        Solution in C++ :

In  C++ :






#include <string>
#include <vector>
#include <map>
#include <list>
#include <iterator>
#include <set>
#include <queue>
#include <iostream>
#include <sstream>
#include <stack>
#include <deque>
#include <cmath>
#include <memory.h>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <utility> 
using namespace std;
 
#define FOR(i, a, b) for(int i = (a); i < (b); ++i)
#define RFOR(i, b, a) for(int i = (b) - 1; i >= (a); --i)
#define REP(i, N) FOR(i, 0, N)
#define RREP(i, N) RFOR(i, N, 0)
 
#define ALL(V) V.begin(), V.end()
#define SZ(V) (int)V.size()
#define PB push_back
#define MP make_pair
#define Pi 3.14159265358979

typedef long long Int;
typedef unsigned long long UInt;
typedef vector <int> VI;
typedef pair <int, int> PII;

VI a[1<<17];
bool was[1<<17];

int n,m;

int dfs(int cur)
{
	if (was[cur])
		return 0;
	
	was[cur] = true;
	int res = 1;
	
	REP(i,SZ(a[cur]))
	{
		int nx = a[cur][i];
		
		res += dfs(nx);
	}
	
	return res;
}


int main()
{
//	freopen("in.txt", "r", stdin);
//	freopen("out.txt", "w", stdout);
	
	scanf("%d%d",&n,&m);
	
	REP(i,m)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		
		a[x].push_back(y);
		a[y].push_back(x);
	}
	
	VI all;
	
	REP(i,n)
	{
		if (!was[i])
		{
			all.push_back(dfs(i));
		}
	}
	
	Int res = 0;
	Int sum = 0;
	REP(i, SZ(all))
	{
		res += sum * all[i];
		
		sum += all[i];
	}
	
	cout << res << endl;
	
	return 0;
}
                    

                        Solution in Java :

In  Java :







import static java.lang.Math.*;
import static java.util.Arrays.*;

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) throws IOException {
        new Solution().run();
    }
    StreamTokenizer in;
    PrintWriter out;
    //deb////////////////////////////////////////////////

    public static void deb(String n, Object n1) {
        System.out.println(n + " is : " + n1);
    }

    public static void deb(int[] A) {

        for (Object oo : A) {
            System.out.print(oo + " ");
        }
        System.out.println("");
    }

    public static void deb(long[] A) {

        for (Object oo : A) {
            System.out.print(oo + " ");
        }
        System.out.println("");
    }

    public static void deb(String[] A) {

        for (Object oo : A) {
            System.out.print(oo + " ");
        }
        System.out.println("");
    }

    public static void deb(int[][] A) {
        for (int i = 0; i < A.length; i++) {
            for (Object oo : A[i]) {
                System.out.print(oo + " ");
            }
            System.out.println("");
        }

    }

    public static void deb(long[][] A) {
        for (int i = 0; i < A.length; i++) {
            for (Object oo : A[i]) {
                System.out.print(oo + " ");
            }
            System.out.println("");
        }

    }

    public static void deb(String[][] A) {
        for (int i = 0; i < A.length; i++) {
            for (Object oo : A[i]) {
                System.out.print(oo + " ");
            }
            System.out.println("");
        }

    }
    /////////////////////////////////////////////////////////////

    int nextInt() throws IOException {
        in.nextToken();
        return (int) in.nval;
    }

    long nextLong() throws IOException {
        in.nextToken();
        return (long) in.nval;
    }

    class Pair<X, Y> {

        public X x;
        public Y y;

        public Pair(X x, Y y) {
            this.x = x;
            this.y = y;
        }

        public void setX(X x) {
            this.x = x;
        }

        public void setY(Y y) {
            this.y = y;
        }
    }

    boolean inR(int x, int y) {
        return (x >= 0) && (x < nn) && (y >= 0) && (y < nn);
    }
    static int nn;

    void run() throws IOException {
        //  in = new StreamTokenizer(new BufferedReader(new FileReader("circles.in")));
        //  out = new PrintWriter(new FileWriter("circles.out"));
        in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(new OutputStreamWriter(System.out));
        solve();
        out.flush();
    }
static int[] parent; // n+1
 static int count;
private void init() {
 for (int i = 1; i < parent.length; i++) {
            parent[i]=i;
        }

}

private void union(int st, int en) {
       int ss=par(st),ee=par(en);
       if(ss!=ee){
       parent[ss]=ee;
       count--;
       }
       
    }

    private int par(int th) {
        if(parent[th]==th)return th;
        else {
            int k=par(parent[th]);
            parent[th]=k;
            return k;}
    }  
    void solve() throws IOException {
        //   BufferedReader re= new BufferedReader(new FileReader("C:\\Users\\ASELA\\Desktop\\A.in"));
        //      BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
        int n = nextInt();
      parent= new int[n+1];
      init();
      int l=nextInt();
        for (int i = 0; i < l; i++) {
            int a=nextInt(),b=nextInt();
            union(a+1,b+1);
        }
        long[] A= new long[n+1];
        for (int i = 1; i < n+1; i++) {
            A[par(i)]++;
        }
        
        long ans=(long)n*(long)n;
        for (int i = 1; i < n+1; i++) {
            ans-=A[i]*A[i];
        }
      ans/=2;
        System.out.println(ans);
      
    }
}
                    

                        Solution in Python : 
                            
In  Python3 :







#!/usr/bin/env python

import sys


if __name__ == '__main__':
    N, I = list(map(int, sys.stdin.readline().split()))
    
    # Count astronauts from different countries
    astronauts = [-1] * N
    countries = []
    
    for _ in range(I):
        A, B = list(map(int, sys.stdin.readline().split()))
        
        if astronauts[A] > -1 and astronauts[B] > -1:
            if astronauts[A] != astronauts[B]:
                k = astronauts[B]
                countries[astronauts[A]].extend(countries[k])
                
                for i in countries[k]:
                    astronauts[i] = astronauts[A]
                countries[k] = []
        
        elif astronauts[A] > -1 and astronauts[B] == -1:
            astronauts[B] = astronauts[A]
            countries[astronauts[A]].append(B)
        
        elif astronauts[A] == -1 and astronauts[B] > -1:
            astronauts[A] = astronauts[B]
            countries[astronauts[B]].append(A)
        
        else:
            astronauts[B] = astronauts[A] = len(countries)
            countries.append([A, B])
    
    # Count unpaired astronauts
    
    
    # Count combinations
    x = [len(c) for c in countries if c]
    
    # Count the contributions from the unpaired astronauts
    triangular_number = lambda n: n * (n + 1) // 2
    unpaired = sum(x == -1 for x in astronauts)
    
    total = triangular_number(unpaired - 1)
    total += unpaired * sum(x)
    
    for i in range(len(x) - 1):
        for j in range(i + 1, len(x)):
            total += x[i] * x[j]
    
    print(total)
                    

View More Similar Problems

Array-DS

An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0<=i<N), that can be referenced as A[i] or Ai. Reverse an array of integers. Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this. Example: A=[1,2,3

View Solution →

2D Array-DS

Given a 6*6 2D Array, arr: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print t

View Solution →

Dynamic Array

Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.

View Solution →

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →