01背包问题回溯法和动态规划
2014-07-25 18:14
477 查看
题目要求:
输入背包的容量v和物品的数量n;接下来n 行每行输入两个数字,第一个是物品质量,第二个是物品价值;
输出背包容纳物品的最大价值。
下面直接贴代码:
回溯法
输入:
20 5
4 7
5 8
2 10
5 10
8 16
输出:
44
[b]动态规划法[/b]
输入背包的容量v和物品的数量n;接下来n 行每行输入两个数字,第一个是物品质量,第二个是物品价值;
输出背包容纳物品的最大价值。
下面直接贴代码:
回溯法
#include<iostream>//之前必须知道背包容量和n个物品 #include<algorithm> using namespace std; class Property { public: int weight,profit; double average; friend bool operator<(Property a,Property b) { return a.average>b.average; } }; class Pack { public: Pack(int Q,int n)//构造函数,初始化 { capcity=Q; number=n; property=new Property[n+1]; bestp=cw=cp=0; } ~Pack() { delete []property; } void inputproperty() { for(int i=0;i<number;i++) { cin>>property[i].weight>>property[i].profit; property[i].average=1.0*property[i].profit/property[i].weight; } sort(property,property+number); } int command() { int totalweight=0; int totalvalue=0; for(int i=0;i<number;i++) { totalweight+=property[i].weight; totalvalue+=property[i].profit; } if(totalweight<capcity)return totalvalue; backtrack(0); return bestp; } bool bound(int i) { int currentp=cp; int currentw=capcity-cw; while(currentw>=property[i].weight&&i<number) { currentw-=property[i].weight; currentp+=property[i].profit; i++; } if(i<number) currentp+=1.0*property[i].profit*currentw/property[i].weight; return currentp>bestp; } void backtrack(int i) { if(i>number-1) { if(bestp<cp) bestp=cp; return; } if(cw+property[i].weight<=capcity)//此处必须用<=比较符号,不然会错 { cw+=property[i].weight; cp+=property[i].profit; backtrack(i+1); cw-=property[i].weight; cp-=property[i].profit; } if(bound(i+1)); backtrack(i+1); } private: int capcity,number; Property *property; int cw,cp,bestp; }; int main() { int n,m; while(cin>>n>>m) { Pack object(n,m); object.inputproperty(); cout<<object.command()<<endl; } return 0; }
输入:
20 5
4 7
5 8
2 10
5 10
8 16
输出:
44
[b]动态规划法[/b]
#include<iostream> #include<cstring> using namespace std; int main() { int Capcity,weight; int *w,*p; int profit[200][200]; while(cin>>Capcity>>weight) { memset(profit,0,sizeof(profit)); w=new int[weight+1]; p=new int[weight+1]; for(int i=1;i<=weight;i++) cin>>w[i]>>p[i];//输入重量和价值 for(int i=1;i<=weight;i++) { for(int j=1;j<=Capcity;j++) { if(w[i]>j)profit[i][j]=profit[i-1][j]; else if(profit[i-1][j]<profit[i-1][j-w[i]]+p[i]) profit[i][j]=profit[i-1][j-w[i]]+p[i]; else profit[i][j]=profit[i-1][j]; } } for(int i=1;i<=weight;i++) { for(int j=1;j<=Capcity;j++) { cout<<profit[i][j]<<" "; } cout<<endl; } } return 0; }
相关文章推荐
- 01背包问题--动态规划
- 动态规划三部曲之01背包问题的分析和实现(二)
- 01 背包问题 动态规划
- 动态规划求解01背包相关的基本问题
- 夕拾算法进阶篇:17)01背包和完全背包问题 (动态规划DP)
- 01背包问题(动态规划)
- 01背包问题-动态规划
- 01背包问题【动态规划】
- 01背包问题---动态规划详解
- 动态规划:01背包问题的浅谈
- 动态规划——背包问题1:01背包
- 01背包问题 动态规划
- (1)01背包问题____动态规划
- 01背包问题 动态规划
- 01背包问题 动态规划解法
- 实际问题的算法抽象——动态规划中的01背包问题
- 01背包问题 动态规划 c语言实现
- 夕拾算法进阶篇:18)装箱问题 (01背包_动态规划DP)
- 动态规划、贪心、回溯、分支限界法解0-1背包问题总结
- c语言数据结构:01背包问题-------动态规划