그 위치에서 선택할 수 있는 수의 최대의 합을 cache에 저장하면서 배열의 끝까지 내려가는 dfs이다. 결국 dfs가 모두 끝난 뒤에는 0,0 위치에서 구할 수 있는 최대의 합이 나온다.
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
|
#include <iostream>
#include <string.h>
using namespace std;
int n;
int tr[500][500];
int cache[500][500];
int ans = 0;
int max(int a, int b) { return a > b ? a : b; }
int dfs(int y, int x) {
if (y == n) return 0;
int& ret = cache[y][x];
if (cache[y][x] != -1) return cache[y][x];
ret = tr[y][x];
ret += max(dfs(y + 1, x),dfs(y + 1, x + 1));
return ret;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n;
memset(cache, -1, sizeof(cache));
for (int i = 0; i < n; i++) {
for (int j = 0; j < i + 1; j++) {
cin >> tr[i][j];
}
}
ans = dfs(0, 0);
cout << ans;
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
'알고리즘 > Dynamic Programming' 카테고리의 다른 글
[백준] 로봇 조종하기_2169 (0) | 2020.03.18 |
---|---|
[백준] 연속합_1912 (0) | 2020.03.04 |
[백준] 퇴사_14501 (0) | 2019.08.01 |
[백준] 욕심쟁이 판다_1937 (0) | 2019.07.30 |
[알고리즘 문제해결전략] 동적 계획법 예시 jump (0) | 2019.07.29 |