0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

アルゴリズムとデータ構造 p63 Frog

Posted at

問題

N個の足場があって、i(=0,1,...N-1)番目の足場の高さは、hiで与えられます。最初の0番目の足場にカエルがいて、以下のいずれかの行動を繰り返してN-1番目の足場を目指します。
・足場iから足場i+1へと移動する。コストは、hi - hi+1の絶対値。
・足場iから足場i+2へと移動する。コストは、hi - hi+2
ゴールまで辿り着くまでに要するコストの総和の最小値を求めてください。

解答 自分(正解)

public class Program
{
  public static void Main()
  {
    int n = 7;
    int[] list = new int[] { 2, 9, 4, 5, 1, 6, 10 };
    int[] dp = new int[n];

    //配列の初期化
    dp[0] = 0;
    dp[1] = list[0];

    exec(2);
    var j = 0;
    foreach (int i in dp)
    {
      System.Console.WriteLine("dp[{0}]:{1} ", j, i);
      j++;
    }

    Console.WriteLine("答え:{0}", dp[n - 1]);

    void exec(int index)
    {
      dp[index] = Math.Min(Math.Abs(list[index - 2] - list[index]) + dp[index - 2], Math.Abs(list[index - 1] - list[index]) + dp[index - 1]);
      if (index < n - 1)
      {
        exec(index + 1);
      }
    }
  }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?