다이나믹 프로그래밍 한접시
[백준] 1932번: 정수 삼각형 [C#]
NaZZU
2024. 4. 25. 23:30
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
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 연습장
{
internal class _1932_boj
{
public void boj_1932()
{
int n = int.Parse(Console.ReadLine());
int[][] arr = new int[n][];
for (int i = 0; i < n; i++)
{
arr[i] = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
}
int[][] dp = new int[n][];
for (int i = 0; i < n; i++)
dp[i] = new int[n];
dp[0][0] = arr[0][0];
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
dp[i + 1][j] = Math.Max(dp[i + 1][j], dp[i][j] + arr[i + 1][j]);
dp[i + 1][j+1] = Math.Max(dp[i + 1][j+1], dp[i][j] + arr[i + 1][j+1]);
}
}
Console.WriteLine(dp[n-1].Max());
}
}
}
|
cs |
처음에는 j번째 행이 이후 행의 값들을 모두 순회하며 연산을 진행하는걸로 구현했었다.
결과가 이상하게나오는걸 보고 문제를 다시 읽어본다음, j번째 행이 다음 행의 같은 열, 1칸 뒤의 열만 연산을 진행해야 한다는 걸 확인한 후 코드를 고쳤다.