【背包总结I】
2015-08-03 22:51
281 查看
1. 01背包
1.1求 《= tot 的最大值
1.2 求 == tot ?
1.3 输出一种方案
输出代码的图解
1.1求 《= tot 的最大值
#include <cstring> #include <cmath> #include <queue> #include <stack> #include <list> #include <map> #include <set> #include <string> #include <cstdlib> #include <cstdio> #include <algorithm> using namespace std; const int N = 10, W = 1000; int value , weight ; int dp[W + 1]; int n,tot; int main() { scanf("%d%d",&n,&tot); for(int i=0;i<n;i++) { scanf("%d%d",&value[i],&weight[i]); } memset(dp,0,sizeof(dp)); for(int i=0;i<n;i++) { for(int j=tot;j>=weight[i];j--) { dp[j] = max(dp[j],dp[j-weight[i]] + value[i]); } } printf("%d\n",dp[tot]); return 0; }
1.2 求 == tot ?
#include <iostream> #include <cstring> #include <cmath> #include <queue> #include <stack> #include <list> #include <map> #include <set> #include <string> #include <cstdlib> #include <cstdio> #include <algorithm> using namespace std; const int N = 10, W = 1000; int value , weight ; int dp[W + 1]; int n,tot; int main() { scanf("%d%d",&n,&tot); for(int i=0;i<n;i++) { scanf("%d%d",&value[i],&weight[i]); } memset(dp,-1,sizeof(dp)); dp[0] = 0; for(int i=0;i<n;i++) { for(int j=tot;j>=weight[i];j--) { if(dp[j-weight[i]] >= 0) dp[j] = max(dp[j],dp[j-weight[i]] + value[i]); } } printf("%d\n",dp[tot]); return 0; }
1.3 输出一种方案
输出代码的图解
#include <iostream> #include <cstring> #include <cmath> #include <queue> #include <stack> #include <list> #include <map> #include <set> #include <string> #include <cstdlib> #include <cstdio> #include <algorithm> using namespace std; const int N = 10, W = 1000; int value , weight ; int dp[W + 1]; bool has[W + 1] ; int n,tot; int main() { scanf("%d%d",&n,&tot); for(int i=0;i<n;i++) { scanf("%d%d",&value[i],&weight[i]); } memset(dp,0,sizeof(dp)); memset(has,0,sizeof(has)); // dp[0] = 0; for(int i=0;i<n;i++) { for(int j=tot;j>=weight[i];j--) { /* if(dp[j-weight[i]] >= 0) dp[j] = max(dp[j],dp[j-weight[i]] + value[i]); */ if(dp[j] < dp[j-weight[i]] + value[i]) { dp[j] = dp[j-weight[i]] + value[i]; has[j][i] = true; } } } printf("%d\n",dp[tot]); for(int i=n-1;i>=0;i--) { if(has[tot][i]) { cout << value[i] << " " << weight[i] << endl; tot -= weight[i]; } } return 0; }
相关文章推荐
- CS281: Advanced Machine Learning 第三节 高斯模型
- STM8S精确延时+LED闪烁
- hdfs 客户端挂载,集群间复制
- ROS学习--(十三)编写简单的订阅器(subscriber),编译,测试
- centos 6实现ssh无密码登录的简便方法
- Android基础之Activity四种启动模式和task相关
- Java 打开文件夹
- Contiki例(三)使用etimer定时器激活被阻塞的任务
- UE4信息交互-蓝图类中的信息交互
- Android真机获取root权限,进入data目录
- 0-1背包
- UI 03 关于UITextField键盘遮挡问题
- 【暑假测试3】C HDU 5327 Olympiad
- HDU 3572 【最大流 && 时间区间建图】
- java Date获取 年月日时分秒
- C# 类型转换
- 面向对象设计原则
- 固定位置右下角
- windows环境配置groovy
- 函数参数异同(值传递、指针传递、引用传递)