algorithm/BOJ

BOJ 4781번 사탕가게

_JunHo 2020. 2. 10. 01:31

BOJ : https://www.acmicpc.net/problem/4781

github : https://github.com/junho0956/Algorithm/blob/master/4781/4781/%EC%86%8C%EC%8A%A4.cpp

 

재귀로 dp문제를 푸는 실력이 정말 조금씩이라도 늘고있다는 느낌을 받아서 기분 좋습니다..ㅠㅠ

 

cash 를 현재 가진 돈이라고 가정했을 때 dp[cash] 를 이용해서 

현재 가진 돈으로 구매할 수 있는 사탕에 대한 모든 경우를 확인했습니다.

소수점은 정확히 계산하기 위해 double 로 받은 후 *100을 해서 int형으로 계산하였습니다.

 

** 테스트케이스가 추가되었네요 **

 

아마 *100 으로도 통과하는 소스가 있다는 글이 아니였을까 생각합니다.

*100을 곱할 때 반올림을 고려해서 0.5를 더해주면 통과할 수 있습니다

형식은(int)(double*100+0.5) 입니다

 

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
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
 
long long dp[10001];
pair<intint> arr[5001];
long long ans;
int n;
 
long long solve(int cash) {
    long long& res = dp[cash];
    if (res) return res;
 
    long long val = 0;
    for (int i = 0; i < n; i++) {
        if (cash - arr[i].second >= 0)
            val = max(val, solve(cash - arr[i].second) + arr[i].first);
    }
 
    return res = val;
}
 
int main() {
    ios::sync_with_stdio(0), cin.tie(0);
 
    while (1) {
        double m;
        memset(dp, 0sizeof(dp));
        cin >> n >> m;
        if (!&& !m) break;
 
        int cash = m * 100;
        for (int i = 0; i < n; i++) {
            int a;
            double b;
            cin >> a >> b;
            arr[i].first = a, arr[i].second = b * 100;
        }
 
        cout << solve(cash) << "\n";
    }
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter