0-1背包问题:(回溯算法)
来源:互联网 发布:stc单片机rst电路原理 编辑:程序博客网 时间:2024/05/22 12:59
#include <iostream>
#define N 205
using namespace std;
double w[N],v[N];
double CurW=0;
double CurV=0;
double c;
double BestV=0;
int BestX[N];
int x[N];
int n;
void backtrack (int t)
{
if (t==n){
if(CurV>BestV){
BestV=CurV;
for(int i=0;i<n;i++)
BestX[i]=x[i];
}
}
else
for(int i=0;i<=1;i++){
x[t]=i;
if(i==0)
backtrack(t+1);
else if((CurW+w[t])<=c)
{
CurW+=w[t];
CurV+=v[t];
backtrack(t+1);
CurW-=w[t];
CurV-=v[t];
}
}
}
int main()
{
cout<<"物品个数和背包容量:";
cin>>n,cin>>c;
cout<<n<<"个物品的重量:";
for(int i=0;i<n;i++)
cin>>w[i];
cout<<n<<"个物品的价值:";
for(int i=0;i<n;i++)
cin>>v[i];
backtrack(0);
cout<<endl<<"背包可装最大价值:";
cout<<BestV<<endl;
cout<<"可行方案:";
for(int i=0;i<n;i++)
cout<<BestX[i]<<" ";
cout<<endl;
return 0;
}
/*
0-1背包问题:
5 10
2 2 6 5 4
6 3 5 4 6
*/
- 0-1背包问题:(回溯算法)
- 0-1背包问题:(回溯算法)
- 0-1背包问题(回溯算法)
- 回溯算法之0-1背包问题
- 0-1背包问题(回溯算法多个数组)
- 回溯算法--背包问题
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯法)
- 0-1背包问题(回溯+暴力)
- 经典算法9:回溯法之0--1背包问题
- 算法java实现--回溯法--0-1背包问题
- 0-1背包问题-回溯&贪心算法-C#Demo
- 01背包问题(回溯算法实现)
- 01背包问题(回溯算法实现)
- Android_Menu
- 虚拟机管理
- Linux入门学习——ssh基础操作
- 方法就是完成特定功能的代码块。 方法的格式: 修饰符 返回值的类型 方法名(参数类型 参数名1,参数类型 参数名2、、、、、、、、、 ){ 方法体; Return 返回值; } 赋值调用的格式:
- Python中使用SMTP发送邮件以及POP收取邮件
- 0-1背包问题:(回溯算法)
- linux使用C++11 thread的问题
- enable kdump on fedora server 27
- C++风格_const用法
- 无题
- 8、16、32-BIT系列单片机区别与特点
- 置 IDEA 中的 Tab 键为 4 个空格
- 掌柜大作战(3):SpringMVC中只对外暴露1个Controller
- golang写的反弹shell(自作孽不可活,切记,切记!)