출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

백준 11052 카드 구매하기(dynamic programming)

알고리즘

by 장동균 2020. 4. 19. 18:22

본문

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
33
34
#include <iostream>
#include <algorithm>
 
using namespace std;
 
int n;
int card[1001];
int dp[1001];
 
void maxPrice()
{
    for (int i = 1; i < n + 1; i++)
    {
        for (int j = 1; j < i + 1; j++)
        {
            dp[i] = max(dp[i], dp[i - j] + card[j]);
        }
    }
    cout << dp[n];
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin >> n;
    for (int i = 1; i < n + 1; i++)
    {
        int tmp;
        cin >> tmp;
        card[i] = tmp;
    }
    maxPrice();
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

n개의 카드를 뽑는 다는 가정을 하는 경우. n-1개의 카드와 1개의 카드, n-2개의 카드와 2개의 카드, n-3개의 카드와 3개의 카드..... 이 모든 경우를 고려해야 된다. 이 때문에 dp[i]=max(dp[i], dp[i-j]+card[j]) 라는 점화식이 나오게 된다.

관련글 더보기

댓글 영역