2546 饭卡(01背包,挺好的)
来源:互联网 发布:军工大数据龙头股票 编辑:程序博客网 时间:2024/05/17 07:02
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=2546
思路:刚开始直接把背包的容量搞为m-5+max1(max1的值为最贵的菜的价格),因为他最多的能花这么多,结果错了,应该把最大的单独提出来,用5块来买,剩下的钱做背包
AC代码:
#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <queue>#include <stack>#include <map>#include <cstring>#include <climits>#include <cmath>#include <cctype>const int inf = 0x3f3f3f3f;//1061109567typedef long long LL;#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1using namespace std;int dp[1000];int a[1010];int main(){ int n; while(scanf("%d",&n) && n) { memset(dp,0,sizeof(dp)); int max1 = -1; int k; for(int i=1; i<=n; i++) { scanf("%d",&a[i]); if(a[i] > max1) { max1 = a[i]; k = i; } } int x; scanf("%d",&x); if(x < 5) { printf("%d\n",x); continue; } x -= 5; for(int i=1; i<=n; i++) { if(i == k) continue; for(int j=x; j>=a[i]; j--) { dp[j] = max(dp[j],dp[j-a[i]] + a[i]); } } printf("%d\n",x+5-dp[x]-max1); } return 0;}
错误代码:(这个会造成价值最大的有可能没有选,逻辑不对)
#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <queue>#include <stack>#include <map>#include <cstring>#include <climits>#include <cmath>#include <cctype>const int inf = 0x3f3f3f3f;//1061109567typedef long long LL;#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1using namespace std;int dp[1060];int a[1010];int main(){ int n; while(scanf("%d",&n) && n) { memset(dp,0,sizeof(dp)); int max1 = 0; for(int i=1; i<=n; i++) { scanf("%d",&a[i]); if(a[i] > max1) max1 = a[i]; } int cost; scanf("%d",&cost); int x = cost; if(cost < 5) { printf("%d\n",cost); continue; } cost = cost - 5 + max1; for(int i=1; i<=n; i++) { for(int j=cost; j>=a[i]; j--) { dp[j] = max(dp[j],dp[j-a[i]]+a[i]); } } printf("%d\n",x-dp[cost]); } return 0;}
0 0
- 2546 饭卡(01背包,挺好的)
- poj Washing Clothes挺好的一道01背包
- 挺好的~
- 挺好的
- 算法复杂度(挺好的比喻)
- java环境变量(总结的挺好)
- java环境变量(总结的挺好)
- java环境变量(总结的挺好)
- 算法复杂度(转) 挺好的比喻。
- 0.9poj1828(排序挺好的题)
- “谷歌”挺好听的!
- java挺好的
- 挺好的网站
- 挺好的一段话
- 做做题挺好的!
- 灰蒙蒙的,挺好
- 都挺好的
- 挺好的 生活
- 更新到Xcode 7.3 #import 不提示的问题
- MFC+OpenCV打开图像
- 《leetCode》:Kth Largest Element in an Array
- iOS开发学习之 - 深入学习UIButton(2)
- Java-Eclipse编辑窗口不见了
- 2546 饭卡(01背包,挺好的)
- 嵌入式linux常用shell指令
- Androdi AsyncTask
- Whu oj 1609 - Han Move
- 函数指针
- Linux下硬链接和软链接
- 第七周项目1-点类-成员函数
- HDU 1978 How many ways 记忆化dfs+dp
- C#中常用容器的使用与底层数据结构