HDU2546【01背包问题模板题】
来源:互联网 发布:第二个爸爸知乎 编辑:程序博客网 时间:2024/06/05 20:44
饭卡
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16844 Accepted Submission(s): 5855
Problem Description
电子科大本部食堂的饭卡有一种很诡异的设计,即在购买之前判断余额。如果购买一个商品之前,卡上的剩余金额大于或等于5元,就一定可以购买成功(即使购买后卡上余额为负),否则无法购买(即使金额足够)。所以大家都希望尽量使卡上的余额最少。
某天,食堂中有n种菜出售,每种菜可购买一次。已知每种菜的价格以及卡上的余额,问最少可使卡上的余额为多少。
Input
多组数据。对于每组数据:
第一行为正整数n,表示菜的数量。n<=1000。
第二行包括n个正整数,表示每种菜的价格。价格不超过50。
第三行包括一个正整数m,表示卡上的余额。m<=1000。
n=0表示数据结束。
Output
对于每组输入,输出一行,包含一个整数,表示卡上可能的最小余额。
Sample Input
15051 2 3 2 1 1 2 3 2 110050
Sample Output
-4532
Source
UESTC 6th Programming Contest Online
【题目链接】:http://acm.hdu.edu.cn/showproblem.php?pid=2546
【题意】:不多说,讲的很明白
【思路】:首先拿出5元去买最贵的菜,剩余的钱用背包去做就好了。
【代码】:
1.空间未优化过的版本
#include <iostream>#include <stdio.h>#include <cstring>#include <algorithm>#include <cmath>using namespace std;//动态规划版本,没有优化过int n,m,p[1005],dp[1005][1005],id;int main(){ while(scanf("%d",&n)&&n){ for(int i=1;i<=n;++i){ scanf("%d",&p[i]); } scanf("%d",&m); if(m<5){ printf("%d\n",m); continue; } sort(p+1,p+n+1); memset(dp,0,sizeof(dp)); for(int i=1;i<n;++i) for(int j=p[i];j<=m-5;++j){ dp[i][j]=max(dp[i-1][j],dp[i-1][j-p[i]]+p[i]); id=i; } printf("%d\n",m-p[n]-dp[id][m-5]); } return 0;}2.空间优化过的版本
#include <iostream>#include <stdio.h>#include <cmath>#include <algorithm>#include <cstring>using namespace std;//空间优化版本int n,m,p[1005],dp[1005];int main(){ while(scanf("%d",&n)&&n) { //printf("1\n"); for(int i=1; i<=n; ++i) scanf("%d",&p[i]); scanf("%d",&m); sort(p+1,p+n+1); if(m<5) { printf("%d\n",m); continue; } memset(dp,0,sizeof(dp)); for(int i=1; i<n; ++i) for(int j=m-5; j>=0; --j) { if(j>=p[i]) dp[j]=max(dp[j],dp[j-p[i]]+p[i]); } printf("%d\n",m-dp[m-5]-p[n]); } return 0;}
0 0
- HDU2546【01背包问题模板题】
- hdu2546 饭卡 01-背包问题
- HDU2546饭卡//01背包问题
- hdu2546 饭卡 01背包问题
- 饭卡 hdu2546 背包问题
- hdu2546 饭卡 (背包问题)
- HDU2546 01背包
- HDU2546:饭卡(01背包)
- hdu2546 饭卡 (01背包)
- hdu2546饭卡-01背包
- hdu2546饭卡 (01背包)
- HDU2546:饭卡(01背包)
- HDU2546 饭卡 01背包
- hdu2546 01背包
- HDU2546 (01背包)
- HDU2546 饭卡(01背包)
- HDU2546 01背包
- 【HDU2546】饭卡(01背包)
- Mysql:is not allowed to connect to this MySQL server
- 插入算法(C语言)
- 每日一“结”(3)
- Leet Code 11 Container With Most Water
- Linux中文乱码问题
- HDU2546【01背包问题模板题】
- iOS实现带历史记录功能的计算器
- Hat's Fibonacci 1250 (大数+数学 好题)
- java笔记——初识面向对象04继承
- 批判Rust语言,以及C/C++为什么永远不会死
- iOS的输入事件
- Android屏幕适配
- GMM-HMM语音识别
- JS 获取某个时间距离现在时间有多少时分秒