알고리즘/문제풀이
[DP] 정수 삼각형
lipnus
2019. 1. 15. 22:40
반응형
백준 1932 정수삼각형
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int[][] triangle;
static int N;
static int[][] D;
public static void main(String[] args) throws Exception {
//N개의 정수를 배열로 받음
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = null;
N = Integer.parseInt( br.readLine() );
triangle = new int[N][N];
D = new int[N][N];
for(int i=0; i<N; i++) {
st = new StringTokenizer(br.readLine());
for(int j=0; j<i+1; j++) {
triangle[i][j] = Integer.parseInt(st.nextToken());
if(i==0) {
D[i][j] = triangle[0][0];
continue;
}
if(j==0) D[i][j] = triangle[i][j] +D[i-1][j];
else D[i][j] = triangle[i][j] + Math.max( D[i-1][j-1] , D[i-1][j] );
}
}
int max=0;
for(int i=0; i<N; i++) {
if(max<D[N-1][i]) max=D[N-1][i];
}
System.out.println( max );
}
}
반응형