맨 위층 7부터 시작해서 아래에 있는 수 중 하나를 선택하여 아래층으로 내려올 때, 이제까지 선택된 수의 합이 최대가 되는 경로를 구하는 프로그램을 작성하라. 아래층에 있는 수는 현재 층에서 선택된 수의 대각선 왼쪽 또는 대각선 오른쪽에 있는 것 중에서만 선택할 수 있다.
삼각형의 크기는 1 이상 500 이하이다. 삼각형을 이루고 있는 각 수는 모두 정수이며, 범위는 0 이상 9999 이하이다.
입력
첫째 줄에 삼각형의 크기 n(1 ≤ n ≤ 500)이 주어지고, 둘째 줄부터 n+1번째 줄까지 정수 삼각형이 주어진다.
출력
첫째 줄에 합이 최대가 되는 경로에 있는 수의 합을 출력한다.
예제 입력/출력
예제 입력
예제 출력
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
30
알고리즘 분류
● 다이나믹 프로그래밍
소스코드
package Lv2_Silver;
import java.io.*;
import java.util.*;
/**
* @author HanHoon
* @category 다이나믹 프로그래밍
* https://www.acmicpc.net/problem/1932
*/
public class BOJ_S1_1932_정수_삼각형 {
static int[][] arr;
static int[][] dp;
static int N;
public static int find(int depth, int idx){
// 마지막 행에서 dp값 반환
if(depth == N - 1)
return dp[depth][idx];
// 탐색하지 않았을 때 양 쪽 값 비교
if(dp[depth][idx] == 0)
dp[depth][idx] = Math.max(find(depth+1, idx), find(depth+1, idx+1)) + arr[depth][idx];
return dp[depth][idx];
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = null;
StringBuilder str = new StringBuilder();
// N: 삼각형의 크기
N = Integer.parseInt(br.readLine());
arr = new int[N][N];
dp = new int[N][N];
for (int n = 0; n < N; n++){
st = new StringTokenizer(br.readLine());
for(int j = 0; j < n+1; j++)
arr[n][j] = Integer.parseInt(st.nextToken());
}
for(int i = 0; i < N; i++)
dp[N-1][i] = arr[N-1][i];
str.append(find(0,0));
System.out.print(str);
br.close();
}
}
댓글