AOJ本の読書メモ   AOJ    次のAOJの問題へ    前のAOJの問題へ

DPL_1_B: 0-1 Knapsack Problem


問題へのリンク


C#のソース

using System;
using System.Collections.Generic;
using System.Linq;

// Q074 0-1 ナップザック問題 https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_1_B&lang=jp
class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("4 5");
            WillReturn.Add("4 2");
            WillReturn.Add("5 2");
            WillReturn.Add("2 1");
            WillReturn.Add("8 3");
            //13
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("2 20");
            WillReturn.Add("5 9");
            WillReturn.Add("4 10");
            //9
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    struct VWInfoDef
    {
        internal int V;
        internal int W;
    }
    static List<VWInfoDef> mVWInfoList = new List<VWInfoDef>();

    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;

        foreach (string EachStr in InputList.Skip(1)) {
            SplitAct(EachStr);
            VWInfoDef WillAdd;
            WillAdd.V = wkArr[0];
            WillAdd.W = wkArr[1];
            mVWInfoList.Add(WillAdd);
        }

        // 最大価値[重さ合計]なDP表
        int?[] DPArr = new int?[UB + 1];
        DPArr[0] = 0;

        foreach (VWInfoDef EachVWInfo in mVWInfoList) {
            for (int I = UB; 0 <= I; I--) {
                if (DPArr[I].HasValue == false) continue;

                int NewInd = I + EachVWInfo.W;
                if (UB < NewInd) continue;
                int NewVal = DPArr[I].Value + EachVWInfo.V;

                if (DPArr[NewInd].HasValue) {
                    if (DPArr[NewInd].Value < NewVal) {
                        DPArr[NewInd] = NewVal;
                    }
                }
                else {
                    DPArr[NewInd] = NewVal;
                }
            }
        }
        Console.WriteLine(DPArr.Max());
    }
}


解説

動的計画法で解いてます。