AOJ本の読書メモ
AOJ
次のAOJの問題へ
前のAOJの問題へ
DPL_1_C: Knapsack Problem
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
// Q078 ナップザック問題 https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_1_C&lang=jp
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("4 8");
WillReturn.Add("4 2");
WillReturn.Add("5 2");
WillReturn.Add("2 1");
WillReturn.Add("8 3");
//21
}
else if (InputPattern == "Input2") {
WillReturn.Add("2 20");
WillReturn.Add("5 9");
WillReturn.Add("4 10");
//10
}
else if (InputPattern == "Input3") {
WillReturn.Add("3 9");
WillReturn.Add("2 1");
WillReturn.Add("3 1");
WillReturn.Add("5 2");
//27
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
struct ItemInfoDef
{
internal int V;
internal int W;
}
static void Main()
{
List<string> InputList = GetInputList();
int[] wkArr = { };
Action<string> SplitAct = pStr =>
wkArr = pStr.Split(' ').Select(pX => int.Parse(pX)).ToArray();
SplitAct(InputList[0]);
int W = wkArr[1];
int UB = W;
var ItemList = new List<ItemInfoDef>();
foreach (string EachStr in InputList.Skip(1)) {
SplitAct(EachStr);
ItemInfoDef WillAdd;
WillAdd.V = wkArr[0];
WillAdd.W = wkArr[1];
ItemList.Add(WillAdd);
}
// 最大価値[重さ合計]なDP表
int[] DPArr = new int[UB + 1];
foreach (ItemInfoDef EachItemInfo in ItemList) {
for (int I = 0; I <= UB; I++) {
int NewInd = I + EachItemInfo.W;
if (UB < NewInd) break;
int NewVal = DPArr[I] + EachItemInfo.V;
if (DPArr[NewInd] < NewVal) {
DPArr[NewInd] = NewVal;
}
}
}
Console.WriteLine(DPArr.Max());
}
}
解説
配るDPで解いてます。