Journey to the Moon Hackerrank Solved!

Hackerrank link: https://www.hackerrank.com/challenges/journey-to-the-moon
It's a dynamic programming problem.
The basic idea of my solution is:
1: count each group having astronauts from the same country and save in a dictionary
2. It has following solution pattern:
  If let S(n) = a solution for the n groups, let G(n) = a number of astronauts in the n-th group,
   S(0) = 0
   S(1) = 0
   S(2) = S(1) G(1) * G(2)
   S(3) = S(2) + G(2) * G(3)
   ...
   S(n) = S(n-1) + G(n-1) * G(n).


using System;
using System.Collections.Generic;
using System.IO;
class Solution {
        // dictionary grouping astronauts by country and its astronauts count
        static Dictionary<int,List<int>> pairs = new Dictionary<int,List<int>>();
        static bool[] visited; // backtracking for the visited astrounauts
        static int a; // astronauts

        static void Main(String[] args)
        {
            var p = Array.ConvertAll(Console.ReadLine().Split(new[] { ' ' }), Int32.Parse);
            a = p[0]; //astronauts
            visited = new bool[a];

            for (int i = 0; i < a; i++)
            {
                pairs[i] = new List<int>();
            }
            var l = p[1]; //lines

            for (int a0 = 0; a0 < l; a0++)
            {
                var ins = Array.ConvertAll(Console.ReadLine().Split(new[] { ' ' }), Int32.Parse);
                pairs[ins[0]].Add(ins[1]);
                pairs[ins[1]].Add(ins[0]);
            }

            // group, group count
            var dic = new Dictionary<int, int>();
            var group = 0;
            for (int i = 0; i < a; i++)
            {
                if (!visited[i])
                {
                    var groupCount = MarkSameAstronautGroup(i);
                    dic.Add(group++, groupCount+1);
                }
            }

            long s = 0;
            int pc = dic[0]; //previous astronauts count
            for (int i = 1; i < group; i++)
            {
                s += pc * dic[i];
                pc += dic[i];
            }

            Console.WriteLine(s);
        }
        static int MarkSameAstronautGroup(int id)
        {
            if (visited[id])
            {
                return 0;
            }

            visited[id] = true;
            int count = 0;

            // go through astronauts in the same group
            for (int i = 0; i < pairs[id].Count; i++)
            {
                // find an astrounaut not visited yet
                if (!visited[pairs[id][i]]) 
                {
                    count++;
                    count += MarkSameAstronautGroup(pairs[id][i]);
                }
            }
            return count;
        } 
}

Comments

Popular Posts