贪心算法,(其实是很简单很简单的算法,就是排序然后按顺序取就完事)顾名思义,我们每次都要贪婪地得到最好的,但是既然是最好的肯定有个比较标准,体现在算法中也就是特定的排序函数,我们利用此排序函数对集合进行排序。接下来就是每次都从拍好序的集合中找到我们想要的。
在部分背包问题中,贪心算法不会像在0-1背包问题那样浪费任何容量。因此,总是能给出最优解。
代码如下:
/*
背包问题 贪心
不要忘记给结构体内变量赋初值
变量为double类型
*/
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
struct ware {
int num;//物品序号
double P;//效益
double W;//重量
double p_w;//单位效益
ware()
{
num = 0;
P = 0.0;
W = 0.0;
p_w = 0.0;
}
};
struct Bag {
int num;//背包号码
double weight;//重量(单位化)
Bag() { num = 0; weight = 0.0; }
};
bool cmp(ware a, ware b)//从大到小排列
{
return a.p_w > b.p_w;
}
int main()
{
int n;
double M;
cin >> n >> M;
vector<ware> W_P(n);//可以用变量值初始化
for (int i = 0; i < n; i++)
{
//此种方式事前不必定义大小或大小随意
ware temp;
temp.num = i + 1;//背包号码
cin >> temp.P >> temp.W;
temp.p_w = temp.P / temp.W;
W_P.push_back(temp);
//当不会发生越界的时候可用此种方式
/*
cin >> W_P[i].P >> W_P[i].W;
W_P[i].p_w = W_P[i].P / W_P[i].W;
W_P[i].num = i + 1;
*/
}
sort(W_P.begin(), W_P.end(), cmp);
cout << "排好序的结果为:" << endl;
for (int i = 0; i < n; i++)
{
cout << W_P[i].num << " " << W_P[i].p_w << endl;
}
vector<Bag> J(n);
for (int i = 0; i < n; i++)
{
if (W_P[i].W < M)
{
M = M - W_P[i].W;
J[i].num = W_P[i].num;
J[i].weight = 1.0;
}
else {
J[i].num = W_P[i].num;
J[i].weight = M / W_P[i].W;
break;
}
}
int i = 0;
cout << "背包问题最优结果为:" << endl;
while (J[i].num != 0)
{
cout << J[i].num << " " << J[i].weight << endl;
i++;
}
return 0;
}
动态规划
(其实动态规划也不难,真心不难)
如果可以证明最优性原理适用,就可以使用动态规划解决0-1背包问题。
最优性原理是指“