您的位置:首页 > 其它

北工大算法 作业2 动态规划 01背包问题

2018-04-03 16:20 316 查看
可以参考下面的文章 思路写的比较清晰 https://blog.csdn.net/u010293698/article/details/48979623 https://blog.csdn.net/sinat_22991367/article/details/51861373

给定n种物品和一个背包,物品i的重量是wi,其价值为vi,背包的容量为C。背包问题是如何选择装入背包的物品,使得装入背包中物品的总价值最大?
如果在选择装入背包的物品时,对每种物品i只有两种选择:装入背包或不装入背包,即不能将物品i装入背包多次,也不能只装入物品i的一部分,则称为0/1背包问题。
// 作业2 01背包.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <memory>
#include <string>
#include <array>
#define MAX 100
using std::ifstream;
using std::vector;
using std::endl;
using std::cout;
using std::max;
using std::make_shared;
using std::shared_ptr;
using std::string;
class Object
{
public:
int weight;
int value;
};
//最后一个值是容量 剩下的 一个重量 一个价值
int main()
{
for (int i = 0; i < 5; i++)
{
cout << "第"<<i+1<<"组数据"<<endl;
string path = "input_assign01_01.dat";
path[16] += i;
ifstream infile;
infile.open(path);
if (!infile)
{
cout << "error" << endl;
}
int temp;
vector<int> v;
while (infile >> temp)
{
v.push_back(temp);
}
shared_ptr<vector<Object>> oj = make_shared<vector<Object>>();

int f[MAX][MAX];//前面的下标代表选取东西个数 后一个代表
int num, C;//一共多少东西和背包的容量
int count = 0;
Object oo;
for (auto x = v.cbegin(); x != v.cend(); x++)
{

if (x == v.cend() - 1)
{
C = *x;
cout << "背包容量:" << C << endl;
break;
}
if (count == 0) //先value后weight
{
oo.value = *x;
cout << "价值:" << oo.value << " ";
count = 1;
}
else
{
oo.weight = *x;
cout << "质量:" << oo.weight << endl;
count = 0;
oj->push_back(oo);

}
//oj->push_back(oo);
}

num = oj->size();
//cout << num << endl;
for (int i = 0; i <= num; i++)
{

for (int j = 0; j <= C; j++)
{
f[i][j] = 0;
}
}

for (int i = 1; i <= num; i++)
{
for (int j = oj->
4000
;at(i - 1).weight; j <= C; j++)
{
f[i][j] = max(f[i - 1][j], f[i - 1][j - oj->at(i - 1).weight] + oj->at(i - 1).value);
//cout << "f["<<i<<"]"<<"["<<j<<"]"<<f[i][j] << endl;
}
}
cout << "最大价值:" << f[num][C] << endl;
infile.close();
}
system("pause");
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: