https://www.acmicpc.net/problem/1932
동적계획법
문제 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 위 그림은 크기가 5인 숫자 삼각형의 한 모습이다. 맨 위층 7부터 시작해서 아래에 있는 수 중 하나를 선택하여 아래층으로 내려올 때, 이제까지 선택된 수의 합이 최대가 되는 경로를 구하는 프로그램을 작성하라. 아래층에 있는 수는 현재 층에서 선택된 수의 대각선 왼쪽 또는 대각선 오른쪽에 있는 것 중에서만 선택할 수 있다. 삼각형의 크기는 1 이상 500 이하이다. 삼각형을 이루고 있는 각 숫자는 모두 정수이며, 범위는 0 이상 9999 이하이다. 입력 첫째 줄에 삼각형의 크기 n(1 ≤ n ≤ 500)이 주어지고, 둘째 줄부터 n+1줄까지 숫자 삼각형이 주어진다. |
code>>
#include<stdio.h>
#include<vector>
int maxDepth = 5;
std::vector<int> memo;
std::vector<int> list;
int Solve(int depth, int sum, int idx)
{
if (idx + depth >= list.size()) return sum;
if (idx + depth + 1 >= list.size()) return sum;
if (memo[idx] != -1) return memo[idx];
int left = Solve(depth + 1, list[idx + depth], idx + depth) + sum;
int right = Solve(depth + 1, list[idx + depth + 1], idx + depth + 1) + sum;
return memo[idx] = left > right ? left : right;
}
int main()
{
scanf("%d", &maxDepth);
int input;
for (int i = 0; i < maxDepth; i++)
{
for (int ii = 0; ii < i + 1; ii++)
{
scanf("%d", &input);
list.push_back(input);
memo.push_back(-1);
}
}
printf("%d\n", Solve(1, list[0], 0));
return 0;
}
'알고리즘 > 백준' 카테고리의 다른 글
1520>내리막길 (0) | 2018.03.10 |
---|---|
2156>포도주 시식 (0) | 2018.02.26 |
1094>막대기 (0) | 2018.02.04 |
2455>지능형 기차 (0) | 2018.02.04 |
2579>계단 오르기 (0) | 2018.01.27 |