Skip to content

Instantly share code, notes, and snippets.

@PatrickDinh
Created September 22, 2016 02:46
Show Gist options
  • Save PatrickDinh/1863a5edb0879ad6cc4a13948d576ccb to your computer and use it in GitHub Desktop.
Save PatrickDinh/1863a5edb0879ad6cc4a13948d576ccb to your computer and use it in GitHub Desktop.
void Main()
{
var linesInFile = File.ReadAllLines(@"C:\Temp\A-large-practice.in");
var testCases = FileParser.Parse(linesInFile.Skip(1).ToArray());
var sw = new Stopwatch();
sw.Start();
foreach (var testCase in testCases)
{
Solver.Solve(testCase);
testCase.Print();
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds + "ms");
}
class Solver
{
public static int[] FindResults(Item[] items, int credit)
{
var leftIndex = 0;
var rightIndex = items.Length - 1;
while (leftIndex < rightIndex)
{
var cost = items[leftIndex].Price + items[rightIndex].Price;
if (cost == credit)
{
var a = items[leftIndex].OriginalIndex;
var b = items[rightIndex].OriginalIndex;
return new int[2] { Math.Min(a, b), Math.Max(a, b) };
}
else if (cost > credit)
{
rightIndex--;
}
else
{
leftIndex++;
}
}
return new int[2];
}
public static void Solve(TestCase testCase)
{
var sortedItems = testCase.Items
.Where(i => i.Price <= testCase.Credit)
.OrderBy(i => i.Price)
.ToArray();
var result = FindResults(sortedItems, testCase.Credit);
testCase.Solution = result;
}
}
class FileParser
{
public static TestCase[] Parse(string[] lines)
{
var testCases = new List<TestCase>();
var counter = 1;
while (lines.Length > 0)
{
var firstThreeLines = lines.Take(3).ToArray();
var testCase = TestCaseParser.Parse(firstThreeLines);
testCase.Index = counter++;
testCases.Add(testCase);
lines = lines.Skip(3).ToArray();
}
return testCases.ToArray();
}
}
class TestCaseParser
{
public static TestCase Parse(string[] lines)
{
var testCase = new TestCase();
testCase.Credit = Int32.Parse(lines[0]);
testCase.NumberOfItems = Int32.Parse(lines[1]);
testCase.Items = ItemParser.Parse(lines[2]);
return testCase;
}
}
class ItemParser
{
public static Item[] Parse(string line)
{
var prices = line.Split(' ');
var items = new List<Item>();
for (var i = 0; i < prices.Length; i++)
{
items.Add(new Item { OriginalIndex = i + 1, Price = Int32.Parse(prices[i])});
}
return items.ToArray();
}
}
class TestCase
{
public int Index { get; set;}
public int Credit { get; set; }
public int NumberOfItems { get; set; }
public Item[] Items { get; set; }
public int[] Solution { get; set; }
public void Print()
{
if (Solution[0] == 0 && Solution[1] == 0)
{
Console.WriteLine("Cannot solve");
}
else
{
Console.WriteLine($"Case #{Index}: {Solution[0]} {Solution[1]}");
}
}
}
class Item
{
public int OriginalIndex { get; set; }
public int Price { get; set;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment