贪心算法——采用重量最轻者先装的贪心选择策略
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct {
int id;
int carry;
}Good;
bool compareGoods(const Good& a, const Good& b) // 在algorithm里,前项小于后项
{
return a.carry < b.carry;
}
void Greedy(vector<Good>& goods, int carrige)
{
vector<Good> choosenGoods;
sort(goods.begin(), goods.end(), compareGoods); // 根据指定方式排序
int currentWeight = 0;
while(currentWeight < carrige && !goods.empty()){
if (goods[0].carry > carrige-currentWeight) break;
else{
currentWeight += goods[0].carry;
Good item = goods[0];
goods.erase(goods.begin()); // 擦除某项,注意标号
choosenGoods.push_back(item);// 引入某项
}
}
cout << "There are " << choosenGoods.size() << " goods chosen" << endl << "Weight " << currentWeight << endl;
cout << "They are ";
for(Good i: choosenGoods){
cout << i.id << " ";
}
cout << endl;
}
int main() {
vector<Good> goods = {{1,5}, {2,4}, {3, 6}, {4,1}, {5, 10}};
Greedy(goods, 13);
return 0;
}