GCJ Africa 2010 - Store Credit
The Store Credit problem in the qualification round of Google Code Jam Africa 2010 is relatively straight forward. You are given a collection of priced items and a credit limit. You are also told that 2 items will exactly add up to given credit limit thus you must find which two items can be purchased. To solve it, just keep a Dictionary (hash table) of prices with the index of the item that carries that price as you traverse the price listing. By doing this you can work out - in constant time - if the "complementary price", that is the price that takes you up to the credit limit, is in the list and if so what it's index is. Furthermore the program bails out as soon as it has found the item pair that satisfies the credit limit. We know this approach must terminate with a feasible solution because the problem states that there is guaranteed to be exactly one pair that solves the problem. Just be careful with your indexes here. Collections in C# and Java are zero-based, but this item list is a 1-based list [you can tell that from the examples given in the problem definition] so you need to be a bit careful with your indexes.
Here's some simple C# code that solves it [running time is O(n) for a list of n items]:
using System;
using System.Collections.Generic;
using System.IO;
namespace GoogleCodeJam.Africa2010.StoreCredit
{
class Program
{
static void Main()
{
const string basePath = @"C:\";
var infile = new StreamReader(basePath + "large.txt");
var outfile = new StreamWriter(basePath + "output.txt");
int n = Int32.Parse(infile.ReadLine());
for (int caseNo = 1; caseNo <= n; caseNo++)
{
int C = Int32.Parse(infile.ReadLine()); // credit
int I = Int32.Parse(infile.ReadLine()); // item count
var P = infile.ReadLine().Split(new[] { ' ' }); // prices
var priceIndexMap = new Dictionary<int, int>();
int k = -1;
int j = 0;
for (; j < P.Length; j++ )
{
int currentPrice = Int32.Parse(P[j]);
if (priceIndexMap.ContainsKey(C - currentPrice))
{
k = priceIndexMap[C - currentPrice];
break;
}
if (!priceIndexMap.ContainsKey(currentPrice))
priceIndexMap.Add(currentPrice, j + 1);
}
j++;
if (j < k)
outfile.WriteLine("Case #{0}: {1} {2}", caseNo, j, k);
else
outfile.WriteLine("Case #{0}: {1} {2}", caseNo, k, j);
}
infile.Close();
outfile.Close();
}
}
}
18 Apr 2010 Damien Wintour







