0-1背包问题
给定n个物品和一个容量为C的背包,物品i的重量是wi,其价值是vi,0-1背包问题要求从这n个物品中,选择装入背包的最优组合(物品不可以分割),使得装入背包中的物品的总价值最大。
例如,将8件物品放入容量为15的背包,8件物品的重量和价值分别为:
W = {7, 4, 4, 6, 2, 2, 3, 5}
V = {8, 7, 5, 7, 1, 5, 4, 6}
对0-
1背包问题,可以设计多种贪心策略,如:
重量最轻的物品优先的贪心策略。
价值最大的物品优先的贪心策略。
单位价值最大的物品优先的贪心策略。
随机选择物品的贪心策略。
无法数学证明某一种策略的最优性,因此使用贪心法求解0-1背包问题时,必须尽可能多地枚举各种贪心策略,并从各种贪心策略的运行结果中,找出问题的近似最优解。
#include “pch.h”
#include
#include
#include
#include
#include <stdio.h>
#include
#include"cmath"
#include"cstring"
using namespace std;
struct form {
int i; //为方便后序打印结果,设置物品序号
int pi;
int wi;
float xi;
int si;
int flag; //标志一整个物品被选取
float floflag; //标志物品被选取的那一部分
};
int bag=0, t