动态规划(二)HDU1114

1.题目来源HDU1114

Sample Input
3
10 110
2
1 1
30 50
10 110
2
1 1
50 30
1 6
2
10 3
20 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.

2.题目分析

题目首先给定一个空存钱罐的重量和这个存钱罐最多能装进去的重量,现在需要在不打破这个存钱罐的情况下猜测里面最少的钱每种钱的数量不做限制,条件是必须装满,同时给出每种钱币的价值和重量。
参考背包九讲,这属于完全背包问题,初始状态为装满的情况,所以放钱币的策略就变成了放几个问题,有的钱币组合不合理就设置得比较大。

3.代码如下

#include<iostream>
#include<algorithm>
using namespace std;
const int num = 10005;
const int abc = 9999999999;
int main(void)
{
    //(1 <= P <= 50000, 1 <= W <= 10000)
    //1 <= E <= F <= 10000, N (1 <= N <= 500)(coins)
    int dp[num], C[num], W[num], T, N, E, F, V, i, j;
    cin >> T;
    while (T-- > 0) {
        cin >> E >> F;   // the weight of an empty pig and of the pig filled with coins
        cin >> N;       //the number of various coins used in the given currency. 
        V = F - E;      //the rest of the space
                        //C is the value of the coin in monetary units, W is it's weight in grams. 
        for (i = 1; i <= N; i++)
            cin >> W[i] >> C[i];    
        dp[0] = 0;
        for (i = 1; i <= V; i++) dp[i] = abc;
        for (i = 1; i <= N; i++) {
            for (j = C[i]; j <= V; j++) {
                dp[j] = min(dp[j], dp[j - C[i]] + W[i]);
            }
        }
        if (dp[V] == abc) cout << "This is impossible."<<endl;
        else cout << "The minimum amount of money in the piggy-bank is "<<dp[V]<<"."<<endl;
    }
    return 0;
}
posted @   Chasssser  阅读(139)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示