hihoCoder 1043 完全背包
来源:互联网 发布:淘宝名字大全男生 编辑:程序博客网 时间:2024/06/06 01:51
可以直接在0-1背包的基础上进行扩展,得到一个比较naive的解法
// hiho1043.cpp : Defines the entry point for the console application.//#include<iostream>#include<vector>#include<algorithm>#include<fstream>//#define DEBUGusing namespace std;int main(){#ifdef DEBUGifstream cin("E:\\cppfiles\\input.txt");#endifint n, m;cin >> n >> m;vector<int> need(n + 1, 0);vector<int> value(n + 1, 0);for (int i = 1; i <= n; ++i){cin >> need[i] >> value[i];}vector<vector<int> > dp(n + 1, vector<int>(m + 1, 0));for (int i = 1; i <= n; ++i){for (int j = 1; j <= m; ++j){if (j < need[i]){dp[i][j] = dp[i - 1][j];}else{int cnt = 1;int tmp = 0;while (j - cnt*need[i] >= 0){tmp = max(tmp, dp[i - 1][j - cnt*need[i]]+cnt*value[i]);cnt++;}dp[i][j] = max(dp[i - 1][j], tmp);}}}cout << dp[n][m] << endl;return 0;}
注意观察可以得到,其实在每次计算i物品拿j件时,不需要从1开始循环,只要比较下拿j-1时即可,因为之前已经有计算好的结果了,如果从1开始循环,就进行了多余的重复计算。最后再进行空间的优化即可得到如下代码。
// hiho1043.cpp : Defines the entry point for the console application.//#include<iostream>#include<vector>#include<algorithm>#include<fstream>//#define DEBUGusing namespace std;int main(){#ifdef DEBUGifstream cin("E:\\cppfiles\\input.txt");#endifint n, m;cin >> n >> m;vector<int> need(n + 1, 0);vector<int> value(n + 1, 0);for (int i = 1; i <= n; ++i){cin >> need[i] >> value[i];}vector<int> dp(m + 1, 0);for (int i = 1; i <= n; ++i){for (int j = need[i]; j <= m; ++j){dp[j] = max(dp[j], dp[j-need[i]]+value[i]);}}cout << dp[m] << endl;return 0;}
0 0
- hihoCoder 1043 完全背包
- hihoCoder 1043 : 完全背包
- hihoCoder 1043 完全背包
- hihocoder -#1043 : 完全背包
- [HihoCoder]#1043 : 完全背包
- hihocoder #1043 : 完全背包
- hihocoder #1043 完全背包
- Hihocoder #1043 : 完全背包
- hihoCoder 1043 完全背包
- hihoCoder 1043 : 完全背包
- hihocoder 1043 : 完全背包
- hihocoder#1043之完全背包
- hihocoder 1043(完全背包)
- hihocoder #1043 : 完全背包 (DP)
- hihocoder:完全背包
- hihocoder 完全背包
- hihocoder-第七周-完全背包
- hiho一下 第七周 Hihocoder #1043 : 完全背包
- 九度OJ--1007-奥运排序问题
- 堆排序算法总结
- uva 531 Compromise (最长公共子序列)
- (4.4.4)android的组件类
- BZOJ 3620 似乎在梦中见过的样子 KMP+暴力
- hihoCoder 1043 完全背包
- HDU 4288 Coder(线段树单点更新)
- Visual Studio 学习笔记
- SNMP协议详解
- 2015年3月如何免费刷Q币方法有什麽软件可以刷Q币,不要钱刷QB软件
- Java NIO详解及实例和源码下载(二)
- Ubuntu下的Android环境(Eclipse)搭建
- Unsupported major.minor version 52.0
- KMP算法详解