DPコンテスト
次のDPコンテストの問題へ
前のDPコンテストの問題へ
Educational DP Contest E Knapsack 2
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("3 8");
WillReturn.Add("3 30");
WillReturn.Add("4 50");
WillReturn.Add("5 60");
//90
}
else if (InputPattern == "Input2") {
WillReturn.Add("1 1000000000");
WillReturn.Add("1000000000 10");
//10
}
else if (InputPattern == "Input3") {
WillReturn.Add("6 15");
WillReturn.Add("6 5");
WillReturn.Add("5 6");
WillReturn.Add("6 4");
WillReturn.Add("6 6");
WillReturn.Add("3 5");
WillReturn.Add("7 2");
//17
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
struct WVInfoDef
{
internal long W;
internal long V;
}
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]);
long W = wkArr[1];
var WVInfoList = new List<WVInfoDef>();
foreach (string EachStr in InputList.Skip(1)) {
SplitAct(EachStr);
WVInfoDef WillAdd;
WillAdd.W = wkArr[0];
WillAdd.V = wkArr[1];
WVInfoList.Add(WillAdd);
}
// 最小の重さ[価値] なDP表
long UB = WVInfoList.Sum(px => px.V);
long?[] DPArr = new long?[UB + 1];
DPArr[0] = 0;
foreach (WVInfoDef EachWVInfo in WVInfoList) {
for (long I = UB; 0 <= I; I--) {
if (DPArr[I].HasValue == false) continue;
long NewInd = I + EachWVInfo.V;
long NewVal = DPArr[I].Value + EachWVInfo.W;
if (NewVal > W) continue;
if (DPArr[NewInd].HasValue) {
if (DPArr[NewInd].Value <= NewVal) {
continue;
}
}
DPArr[NewInd] = NewVal;
}
}
for (long I = UB; 0 <= I; I--) {
if (DPArr[I].HasValue) {
Console.WriteLine(I);
break;
}
}
}
}
解説
価値の上限が10^3なので、
最小の重さ[価値]なDP表を使ってます。