728x90
1932번: 정수 삼각형
첫째 줄에 삼각형의 크기 n(1 ≤ n ≤ 500)이 주어지고, 둘째 줄부터 n+1번째 줄까지 정수 삼각형이 주어진다.
www.acmicpc.net
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Main m = new Main();
m.doit();
}
int N;
int t[][] = new int[500][500];
int memo[][] = new int[500][500];
public void doit() throws FileNotFoundException{
//System.setIn(new FileInputStream("input.txt"));
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
for(int i = 0; i < N; i++){
for(int j = 0; j < i+1; j++){
t[i][j] = sc.nextInt();
}
}
initMemo();
System.out.println(tri(0, 0));
// for(int i = 0; i < N; i++){
// System.out.println(Arrays.toString(t[i]));
// }
sc.close();
}
int tri(int x, int y){
if(x == N - 1){
return t[x][y];
}
if(memo[x][y] != -1){
return memo[x][y];
}
memo[x][y] = Math.max(tri(x+1, y), tri(x+1, y + 1)) + t[x][y];
return memo[x][y];
}
void initMemo(){
for(int i = 0; i < N; i++){
for(int j = 0; j < i+1; j++){
memo[i][j] = -1;
}
}
}
}
728x90
반응형
'IT 정보 > 알고리즘(백준, BOJ)' 카테고리의 다른 글
[백준-BOJ] 1963 (0) | 2021.02.02 |
---|---|
[백준-BOJ] 1946 (0) | 2021.02.02 |
[백준-BOJ] 1931 (0) | 2021.02.02 |
[백준-BOJ] 1924 (0) | 2021.02.02 |
[백준-BOJ] 1915 (0) | 2021.02.02 |