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)); } }
Bookmark and Share