Journey to the Moon

Sort by

recency

|

23 Discussions

|

  • + 0 comments

    The answer seems wrong.

        long long int totalWays = n*(n-1) / 2;
        long long int sameWays = 0;
        
        for(i=0;i<numComponents;i++)
        {    
            sameWays = sameWays + (eachC[i]*(eachC[i]-1) / 2);
        }
        cout << (totalWays - sameWays) << endl;
        return 0;
    

    after finding components and number on each component, with the same syntax used in the editorial soln, the final calculation should be:

        int the_count = 0, total=0;
        for (i=0;i<numComponents;i++) {
            the_count += eachC[i] * total;
            total += eachC[i];
        }
        return the_count;
    

    This is basically keeping the property of the_count: it is the number of possible interactions until ith component. Addition of each new component creates itself times the total number of nodes; as an addition to previous possibilities.

    This changes half of the test cases.

  • + 0 comments

    The C# boiler plate is broken.

    You need to change the return type from int to long.

  • + 0 comments
    import java.io.*;
    import java.util.*;
    
    public class Solution {
      public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        
        String[] line = br.readLine().split(" ");
        final int N = Integer.parseInt(line[0]);
        
        
        final List<List<Integer>> compatriots = new ArrayList<List<Integer>>(N);
        for(int i = 0; i < N; ++i){
          compatriots.add(new ArrayList<Integer>());
        }
        
        
        for(short L = Short.parseShort(line[1]); L > 0; --L){
          line = br.readLine().split(" ");
          final int A = Integer.parseInt(line[0]);
          final int B = Integer.parseInt(line[1]);
          compatriots.get(A).add(B);
          compatriots.get(B).add(A);
        }
        
        boolean[] isVisited = new boolean[N];
        List<Integer> countrySizes = new ArrayList<Integer>();
        for(int i = 0; i < N; ++i){
          int countrySize = 0;
          final Queue<Integer> q = new ArrayDeque<Integer>();
          q.add(i);
          do {
            int astronautId = q.poll();
            if(!isVisited[astronautId]){
              ++countrySize;
              isVisited[astronautId] = true;
              q.addAll(compatriots.get(astronautId));
            }
          } while (!q.isEmpty());
          if(countrySize > 0){
            countrySizes.add(countrySize);
          }
        }
        
        long numPairs = 0L;
        long numPartners = N;
        for(int countrySize : countrySizes){
          numPairs += countrySize * (numPartners -= countrySize);
        }
        
        System.out.print(numPairs);
      }
    }
    
  • + 0 comments

    Kotlin solution. Note that the return type of journeyToMoon needs to be changed to Long to pass test case 11 which otherwise overflows.

    fun journeyToMoon(n: Int, astronaut: Array<Array<Int>>): Long {
        val nodes = (0..<n).map {Node(it)}
        val visited = mutableSetOf<Node>()
        val groups = mutableListOf<Set<Node>>()
        for (link in astronaut) {
            nodes[link[0]].connections.add(nodes[link[1]])
            nodes[link[1]].connections.add(nodes[link[0]])
        }
        for (node in nodes) {
            if (visited.contains(node)) continue
            val group = findConnections(node)
            groups.add(group)
            visited.addAll(group)
        }
        val sizes = groups.map {it.size.toLong()}
        val allPairs = n.toLong()*(n-1)/2
        val sameCountryPairs = sizes.map {it*(it-1)/2}
            .sum()
        return allPairs - sameCountryPairs
    }
    
    data class Node(val id: Int) {
        val connections = mutableSetOf<Node>()
    }
    
    fun findConnections(start: Node): Set<Node> {
        val visited = mutableSetOf<Node>()
        val queue = ArrayDeque<Node>()
        queue.add(start)
        while (!queue.isEmpty()) {
            val curr = queue.removeFirst()
            visited.add(curr)
            queue.addAll(curr.connections.filter {!visited.contains(it)})
        }
        return visited
    }
    
  • + 0 comments
    from collections import Counter
    
    def journeyToMoon(n, astronaut):
        # Initialize disjoint set (union-find) structures
        root = list(range(n))
        rank = [0] * n
        
        def find_root(a):
            if root[a] != a:
                root[a] = find_root(root[a])  # Path compression
            return root[a]
            
        def union(a, b):
            i, j = find_root(a), find_root(b)
            if i != j:
                if rank[i] > rank[j]:
                    root[j] = i
                elif rank[i] < rank[j]:
                    root[i] = j
                else:
                    root[j] = i
                    rank[i] += 1
        
        # Union all astronaut pairs
        for a, b in astronaut:
            union(a, b)
        
        # Count the size of each connected component
        component_sizes = list(Counter(find_root(i) for i in range(n)).values())
        
        # Calculate the number of valid pairs
        total_pairs = 0
        sum_sizes = 0
        
        for size in component_sizes:
            total_pairs += sum_sizes * size  # Pairs between current and previous components
            sum_sizes += size  # Update the cumulative size sum
        
        return total_pairs