DPコンテスト    次のDPコンテストの問題へ    前のDPコンテストの問題へ

Educational DP Contest A Frog1


問題へのリンク


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("4");
            WillReturn.Add("10 30 40 20");
            //30
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("2");
            WillReturn.Add("10 10");
            //0
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("6");
            WillReturn.Add("30 10 60 10 60 50");
            //40
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();

        int[] HArr = InputList[1].Split(' ').Select(X => int.Parse(X)).ToArray();
        int UB = HArr.GetUpperBound(0);

        // 最小コスト[現在位置] なDP表
        var DPDict = new Dictionary<int, int>();
        DPDict[0] = 0;

        for (int I = 0; I <= UB; I++) {
            if (DPDict.ContainsKey(I) == false) continue;

            Action<int> wkAct = (pNewInd) =>
            {
                if (pNewInd > UB) return;
                int NewVal = DPDict[I] + Math.Abs(HArr[I] - HArr[pNewInd]);

                if (DPDict.ContainsKey(pNewInd)) {
                    if (DPDict[pNewInd] <= NewVal) {
                        return;
                    }
                }
                DPDict[pNewInd] = NewVal;
            };
            wkAct(I + 1); // 1つ先にジャンプする場合
            wkAct(I + 2); // 2つ先にジャンプする場合

            //Console.WriteLine("{0}回目のDPの結果", I);
            //foreach (var EachPar in DPDict) {
            //    Console.WriteLine("DPDict[{0}]={1}", EachPar.Key, EachPar.Value);
            //}
        }
        Console.WriteLine(DPDict[UB]);
    }
}


解説

DPで解いてます。