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 :



title-img


                            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

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →