HDU1114 存钱罐 完全背包

来源:互联网 发布:知乎客户端加载不出来 编辑:程序博客网 时间:2024/06/03 00:54

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1114

给你一个存钱罐的空的质量和存满钱的质量,给你每种硬币的质量和价值,让你算出它的最小价值。

310 11021 130 5010 11021 150 301 6210 320 4
 

Sample Output
The minimum amount of money in the piggy-bank is 60.The minimum amount of money in the piggy-bank is 100.This is impossible.
思路:这道题是一道完全背包的题,不限制硬币的数量,求在一定重量内最小价值。这里使用了没有优化的背包。

#include<iostream>#include<string.h>#include<stdio.h>#include<algorithm>using namespace std;int dp[505][10005];const int inf = (1 << 30) - 1;int main(){    int T,n,i,v,w,l,h,j;    int p[505], m[505];    cin >> T;    while (T--)    {        cin >> l >> h>>n;        h -= l;        memset(p, 0, sizeof(p));        memset(m, 0, sizeof(m));        for (i = 0; i < n; i++)            cin >> p[i] >> m[i];        for (i = 0; i <=n; i++)        {            for (j = 0; j <= h; j++)            {                if ( j == 0)                    dp[i][j] = 0;                else dp[i][j] = inf;            }        }        for(i=0;i<n;i++)        {            for ( j = 0; j <=h; j++)            {                    if (m[i] > j)                        dp[i + 1][j] = dp[i][j];                    else                    dp[i + 1][j] = min(dp[i][j], dp[i + 1][j - m[i]] + p[i]);            }        }        if (dp[n][h] == inf)printf("This is impossible.\n");        else            printf("The minimum amount of money in the piggy-bank is %d.\n", dp[n][h]);    }    return 0;}



原创粉丝点击