hdu 2126 Buy the souvenirs
来源:互联网 发布:软件项目成果 编辑:程序博客网 时间:2024/04/30 03:22
题目连接,点我点我点我
题意: n个物品,m元钱,每个物品最多买一次,问最多可以买几件物品,并且输出方案数。
思路:01背包问题,不过需要加多一维记录已买了多少物品,把买多少件物品看作价值,价钱看作花费,需要注意的是前一次和后一次递推中价值都是相差1的,dp[v][2] ,dp[v][0] 储存原本要记录的 dp ,即买了多少件物品,而 dp[v][1] 则记录方案数目。 dp[i][1] 都要初始化为1,(注意是i!!为了这个错误我不知道跪了多少次~囧rz)当dp[v][0]=0时则输出”Sorry, you can’t buy anything.“,后面的dp[v][1]则不用理会。
#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>#include <algorithm>using namespace std;int dp[505][2];int main(){ int T, m, n; int i, j; int a[35]; scanf("%d", &T); while (T--) { scanf("%d %d", &n, &m); for (i = 1; i <=n; i++) { scanf("%d", &a[i]); } memset(dp, 0, sizeof(dp)); for (i = 0; i <= m; i++) { dp[i][1] = 1; /*因为j可能为零,所以必须从0开始初始化*/ } for (i = 1; i <=n; i++) { for (j = m; j >= a[i]; j--) { if (dp[j][0] < dp[j - a[i]][0] + 1) { dp[j][0] = dp[j - a[i]][0] + 1; dp[j][1] = dp[j - a[i]][1]; } else if (dp[j][0] == dp[j - a[i]][0] + 1) { dp[j][1] = dp[j - a[i]][1] + dp[j][1]; } } } if (dp[m][0] != 0) { printf("You have %d selection(s) to buy with %d kind(s) of souvenirs.\n", dp[m][1], dp[m][0]); } else { printf("Sorry, you can't buy anything.\n"); } } return 0;}
0 0
- hdu 2126 Buy the souvenirs
- hdu 2126 Buy the souvenirs
- Buy the souvenirs(hdu(2126)
- HDU 2126 Buy the souvenirs
- HDU 2126 Buy the souvenirs
- HDU 2126 Buy the souvenirs
- hdu 2126 Buy the souvenirs
- HDU - 2126 Buy the souvenirs
- hdu 2126 Buy the souvenirs
- Buy the souvenirs - HDU 2126 背包dp
- HDU 2126 - Buy the souvenirs(01背包)
- HDU-2126 Buy the souvenirs (DP)
- hdu 2126 Buy the souvenirs 01背包
- 2126 Buy the souvenirs
- HDU 2126 Buy the souvenirs (dp 二维01背包)
- hdu 2126 Buy the souvenirs(二维0/1背包)
- HDU 2126 Buy the souvenirs(DP:01背包)
- hdu 2126 Buy the souvenirs(求方案数)
- How to Improve Speed Reading Skills
- android在代码中利用Spinner控件设置联动地区的解决办法
- iOS9 3DTouch开发 知识点详解
- JAVA类与对象学习笔记
- 怎样存钱利最大
- hdu 2126 Buy the souvenirs
- hdu1860
- Java判断数字是否为整数
- Altium designer的简单学习
- 【FAQ】Mac下,执行sed命令报错:“command c expects \ followed by text”,怎么办?
- PHP TSRM(线程安全管理)详解
- 贝叶斯分类
- 2014 CCF认证 相邻数对(C语言)
- JAVA练习之消费用户折扣卡模拟