다이나믹 프로그래밍 한접시
[백준] 계단 오르기 [C#]
NaZZU
2024. 4. 8. 23:41
계단을 오르지만, 연속으로 최대 2계단만 오를 수 있는 제한이 걸려있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Runtime.Intrinsics.Arm;
namespace 연습장
{
internal class Program
{
static StringBuilder sb = new StringBuilder();
static void Main(string[] args)
{
using var reader = new StreamReader(Console.OpenStandardInput());
using var print = new StreamWriter(Console.OpenStandardOutput());
int n = int.Parse(Console.ReadLine());
int[] dp = new int[n + 1];
dp[0] = 0;
int[] value = new int[n];
for (int i = 0; i < n; i++)
value[i] = int.Parse(Console.ReadLine());
dp[1] = value[0];
if (n == 1)
{
Console.WriteLine(dp[1]);
return;
}
dp[2] = Math.Max(dp[0] + value[0], dp[1] + value[1]);
for (int j = 3; j <= n; j++)
{
dp[j] = Math.Max(dp[j - 3] + value[j - 2] + value[j-1], dp[j - 2] + value[j-1]);
}
Console.WriteLine(dp[n]);
}
}
}
|
cs |
각 계단을 오르는 기회비용을 두 가지의 경우로 나누었다.
첫번째는 2칸을 오른 후, 한칸을 오르는 경우 - dp[j-3] + value[j - 2] + value[j - 1],
두번째는 두칸을 올라 한번에 접근하는 경우 - dp[j - 2] + value[j - 1].
이 두 경우 중 가장 큰 경우를 골라서 출력해 주었다.
그리고 계단의 개수가 1이라면 IndexOutofRange 에러가 나기 때문에, n이 1로 주어졌을 때, 1의 값을 출력하고 바로 함수를 종료해 주었다.