POJ - 1384 Piggy-Bank(01背包)

来源:互联网 发布:c语言fabs函数用法 编辑:程序博客网 时间:2024/05/02 03:08

题目大意:有一个存钱罐,初始重量为E,放完硬币后的重量为F。给出N种硬币,每种硬币都有相应的重量和价值,问这个存钱罐中的钱最少是多少

解题思路:01背包为题,只不过最大值变成了最小值而已,以体积为限制

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 510;const int MAXN = 10010;const int INF = 0x3f3f3f3f;struct Coin{    int val, weight;}C[N];int dp[MAXN];int n, m;bool cmp(const Coin &a, const Coin &b) {    return a.weight < b.weight;}void init() {    int e, f;    scanf("%d%d", &e, &f);    m = f - e;    scanf("%d", &n);    for (int i = 0; i < n; i++)        scanf("%d%d", &C[i].val, &C[i].weight);}void solve() {    sort(C, C + n, cmp);    memset(dp, 0x3f, sizeof(dp));    dp[0] = 0;    for (int i = 0; i < n; i++)        for (int j = C[i].weight; j <= m; j++)            dp[j] = min(dp[j], dp[j - C[i].weight] + C[i].val);    if (dp[m] == INF) printf("This is impossible.\n");    else printf("The minimum amount of money in the piggy-bank is %d.\n", dp[m]);}int main() {    int test;    scanf("%d", &test);    while (test--) {        init();        solve();    }    return 0;}
0 0
原创粉丝点击