AOJ本の読書メモ
AOJ
次のAOJの問題へ
前のAOJの問題へ
DPL_1_A: Coin Changing Problem
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
// Q073 コイン問題 https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_1_A&lang=jp
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("15 6");
WillReturn.Add("1 2 7 8 12 50");
//2
}
else if (InputPattern == "Input2") {
WillReturn.Add("65 6");
WillReturn.Add("1 2 7 8 12 50");
//3
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
int[] wkArr = InputList[0].Split(' ').Select(pX => int.Parse(pX)).ToArray();
int N = wkArr[0];
int UB = N;
int[] CArr = InputList[1].Split(' ').Select(pX => int.Parse(pX)).ToArray();
// 最小枚数[金額]なDP表
int?[] DPArr = new int?[UB + 1];
DPArr[0] = 0;
foreach (int EachCoin in CArr) {
for (int I = 0; I <= UB; I++) {
if (DPArr[I].HasValue == false) {
continue;
}
int NewInd = EachCoin + I;
if (NewInd > UB) break;
int NewVal = DPArr[I].Value + 1;
if (DPArr[NewInd].HasValue) {
if (DPArr[NewInd].Value > NewVal) {
DPArr[NewInd] = NewVal;
}
}
else {
DPArr[NewInd] = NewVal;
}
}
}
Console.WriteLine(DPArr[UB]);
}
}
解説
動的計画法で解いてます。