Uncategorized

GCJ Africa 2010 - T9 Spelling

The T9 Spelling problem in the qualification round of Google Code Jam Africa 2010 is, like the other problems in this round, fairly trivial. For some given text sequences you need to map them to key presses on a numeric key pad provided. You just need to look through each character provided and replace it with the appropriate key press sequence. Here I'm making use of a dictionary to ensure constant time lookup operations for mapping characters to key press sequences, and I track the last key pressed so I know when to insert a "pause" (denoted by a 0).

Here's some simple C# code that solves it [running time is O(n) for strings of size n]:

using System;

using System.Collections.Generic;

using System.IO;

using System.Text;

 

namespace GoogleCodeJam.Africa2010.T9Spelling

{

    class Program

    {

        static void Main()

        {

            const string basePath = @"C:\";

            var infile = new StreamReader(basePath + "large.txt");

            var outfile = new StreamWriter(basePath + "output.txt");

 

            var map = new Dictionary<string, string>

                          {

                              {"a", "2"},

                              {"b", "22"},

                              {"c", "222"},

                              {"d", "3"},

                              {"e", "33"},

                              {"f", "333"},

                              {"g", "4"},

                              {"h", "44"},

                              {"i", "444"},

                              {"j", "5"},

                              {"k", "55"},

                              {"l", "555"},

                              {"m", "6"},

                              {"n", "66"},

                              {"o", "666"},

                              {"p", "7"},

                              {"q", "77"},

                              {"r", "777"},

                              {"s", "7777"},

                              {"t", "8"},

                              {"u", "88"},

                              {"v", "888"},

                              {"w", "9"},

                              {"x", "99"},

                              {"y", "999"},

                              {"z", "9999"},

                              {" ", "0"}

                          };

 

            int n = Int32.Parse(infile.ReadLine());

            for (int caseNo = 1; caseNo <= n; caseNo++)

            {

                var msg = infile.ReadLine();

                var answer = new StringBuilder();

                int last = -1;

                for (int i = 0; i < msg.Length; i++)

                {

                    string mapped = map[msg[i].ToString()];

                    if (mapped[0] == last)

                        answer.Append(" ");

 

                    answer.Append(mapped);

                    last = mapped[0];

                }

                outfile.WriteLine("Case #{0}: {1}",caseNo, answer);

            }

            infile.Close();

            outfile.Close();

        }

    }

}

Uncategorized

Google Code Jam 2009: Crazy Rows

Google Code JamRound 2 kicked off with a simple sorting problem. We are given a matrix of zeros and ones and we need to find the least cost sort of the rows such that there are no ones to the right of the main diagonal with the constraint that only adjacent rows can be swapped.

Since we are only concerned with ones to the right of the main diagonal we only care about the last one in each row, thus when we read in the input we only store the index of the rightmost one. The problem then reduces to sorting this array using only adjacent cell swaps.

I employed a simple greedy algorithm to do this. Starting at row 1, check if it is ok, if not find the first "unallocated" row that could be placed in row 1, then shift this up counting the swaps as we go. The process then moves onto the next row and repeats the process until there are no more rows to sort.

Here's my C# code to solve it:

using System;
using System.IO;

namespace GoogleCodeJam.CrazyRows
{
    class Program
    {
        static void Main()
        {
            const string basePath = "";
            var infile = new StreamReader(basePath + "large.txt");
            var outfile = new StreamWriter(basePath + "output.txt");

            int testCases = Int32.Parse(infile.ReadLine());
            for (int caseNo = 1; caseNo <= testCases; caseNo++)
            {
                int N = Int32.Parse(infile.ReadLine());
                var values = new int[N];
                for (int i = 0; i < N; i++)
                    values[i] = infile.ReadLine().LastIndexOf('1');

                int ans = 0;
                for (int i = 0; i < N; i++)
                {
                    int k = 0;
                    while (values[i+k] > i)
                        k++;

                    for (int j = k; j >0; j--)
                    {
                        int temp = values[i+j];
                        values[i+j] = values[i+j-1];
                        values[i+j-1] = temp;
                        ans++;
                    }
                }
                outfile.WriteLine("Case #{0}: {1}", caseNo, ans);
            }
            infile.Close();
            outfile.Close();
        }
    }
}

And here's my C++ code to solve it:

#include <string>
#include <iostream>

using namespace std;

static void main()
{
    string basePath = "";
    string inFile = basePath + "large.txt";
    string outFile = basePath + "output.txt";

    freopen(inFile.c_str(),"r",stdin);
    freopen(outFile.c_str(),"w",stdout);

    int testCases; cin >> testCases;
    for (int caseNo = 1; caseNo <= testCases; caseNo++)
    {
        int N; cin >> N;
        int values[41];
        for (int i = 0; i < N; i++)
        {
            string M; cin >> M;
            int z = M.find_last_of('1');
            values[i] = z;
        }
        int ans = 0;
        for (int i = 0; i < N; i++)
        {
            int k = 0;
            while (values[i+k] > i)
                k++;

            for (int j = k; j >0; j--)
            {
                int temp = values[i+j];
                values[i+j] = values[i+j-1];
                values[i+j-1] = temp;
                ans++;
            }
        }
        cout << "Case #" << caseNo << ": " << ans << endl;
    }
}

Uncategorized

Google Code Jam 2009: Bribe the Prisoners

Google Code JamThe last puzzle in Round 1C was the Bribe the Prisoners puzzle. In this puzzle we have P consecutive prison cells each of which has exactly 1 prisoner in it, and a list of q prisoners to be released. When a prisoner from this list is released all other prisoners in the block bounded by empty cells, or the end of the section, riot and therefore need to be bribed.

Since this is a combinatorial optimisation problem we could enumerate through all possible combinations of prisoner release schedules but this results in q! run time which is not feasible when q=100. It is, of course, feasible for small problems (q=5) but going that route is only painting yourself into a corner IMHO.

So let's consider what happens when we release a prisoner. Say we initially start with a release list {q1, q2, q3,...,qQ} where 1 <= qi <=P for all i; and we choose qj to be released first. The block of P previously consecutive cells now has a break in it at position j resulting in 2 blocks: [1, (j-1)], and [(j+1), P]. Furthermore it's obvious that the list of prisoners to be released can be partitioned into 2 lists: those less than j, and those greater than j, since only those prisoners in the containing, unbroken cell block need to be considered when evaluating the optimal release plan for the newly created block. The 2 sub-problems created are in fact the same sort of problem we initially had, and thus a recursive approach can be used to find the minimum-cost solution. In essence we have overlapping sub-problems and an optimal substructure. This implies that dynamic programming can be used.

With that in mind let's define ci,j to be the minimum cost of releasing all prisoners in the release list given that prisoner qi and qj have been released. Since the list of Q prisoners to be released is given to us in increasing order we can augment this list with 2 dummy prisoners, located before the first cell, and after the last cell and mark them as already released to make dealing with boundary conditions easier. [This is what lines 30 and 31 below perform.] Our problem now reduces to finding c1,Q, but we still need to define a strategy for calculating ci,j.

Assume that you have multiple prisoners to be released between qi and qj, and, as per the above definition of ci,j, qi and qj have already been released. The cost of releasing the first prisoners in this block is going to be (qj-qi -2) regardless of which prisoner is released first. However, the cost of releasing subsequent prisoners is going to be affected by this decision. Thus the optimal (minimum) release cost can be calculated by :

where z is one of the values provided in set Q.

As well, because we have overlapping sub-problems it's sensible to use function memoisation and since C# supports nullable data types we need not initialize the cache - it will be auto-initialized to null and we use the null value to indicate the function value hasn't yet been assigned.

The astute reader will note that the problem is now stated in terms of Q rather than P. This is highly desirable since P >> Q and you'll find, as I did, that you run into memory problems if you leave the problem in terms of P.

The C# code is shown below:

   1:  using System;
   2:  using System.IO;
   3:   
   4:  namespace GoogleCodeJam.BribeThePrisoners
   5:  {
   6:      class Program
   7:      {
   8:          private static int?[,] answers;
   9:          private static int[] pardoned;
  10:   
  11:          static void Main()
  12:          {
  13:              var basePath = "";
  14:              var infile = new StreamReader(basePath + "large.txt");
  15:              var outfile = new StreamWriter(basePath + "output.txt");
  16:   
  17:              int testCases = Int32.Parse(infile.ReadLine());
  18:              for (int caseNo = 1; caseNo <= testCases; caseNo++)
  19:              {
  20:                  var data = (infile.ReadLine()).Split(' ');
  21:                  int P = Int32.Parse(data[0]), Q = Int32.Parse(data[1]);
  22:                  answers = new int?[Q + 1,Q + 1];
  23:                  pardoned = new int[Q + 2];
  24:                  int i = 1;
  25:                  foreach (var item in (infile.ReadLine()).Split(' '))
  26:                  {
  27:                      pardoned[i] = Int32.Parse(item);
  28:                      i++;
  29:                  }
  30:                  pardoned[0] = 0;
  31:                  pardoned[Q+1] = P+1;
  32:                  outfile.WriteLine(String.Format("Case #{0}: {1}", caseNo, MinCost(1,Q)));
  33:              }
  34:              infile.Close();
  35:              outfile.Close();
  36:          }
  37:   
  38:          static int MinCost(int start, int finish)
  39:          {
  40:              if (finish - start < 0)
  41:                  return 0;
  42:   
  43:              if (answers[start,finish].HasValue)
  44:                  return answers[start,finish].Value;
  45:              
  46:              int min = Int32.MaxValue;
  47:              for (int k = start; k <= finish; k++)
  48:                  min = Math.Min(min, pardoned[finish+1]-pardoned[start-1]-2 + 
  49:                                       MinCost(start, k - 1) + MinCost(k + 1, finish));
  50:              
  51:              answers[start, finish] = min;
  52:              return min;
  53:          }
  54:      }
  55:  }

And for good measure, here's my C++ code:

#include <algorithm>
#include <string>

using namespace std;

int answers[101][101];
int pardoned[102];

int minCost(int start, int finish)
{
    if (finish - start < 0)
        return 0;

    if (answers[start][finish] != -1)
        return answers[start][finish];

    int minimum = 1<<30;
    for (int k = start; k <= finish; k++)
        minimum = min(minimum, pardoned[finish+1]-pardoned[start-1]-2 
+ minCost(start, k - 1) + minCost(k + 1, finish)); answers[start][finish] = minimum; return minimum; } void main() { string basePath = ""; string inFile = basePath + "large.txt"; string outFile = basePath + "output.txt"; freopen(inFile.c_str(),"r",stdin); freopen(outFile.c_str(),"w",stdout); int testCases; scanf("%d", &testCases); for (int caseNo = 1; caseNo <= testCases; caseNo++) { int P, Q; scanf("%d %d", &P, &Q); for(int i=0; i<Q+1; i++) for(int j=0; j<Q+1; j++) answers[i][j] = -1; pardoned[0] = 0; pardoned[Q+1] = P+1; int i; for (i = 1; i <= Q; i++) scanf("%d", &pardoned[i]); printf("Case #%d: %d\n", caseNo, minCost(1, Q)); } }

« Prev - Next »