【C++】最优装载问题

贪心算法——采用重量最轻者先装的贪心选择策略

#include 
#include 
#include 

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& goods, int carrige)
{
    vector 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 goods = {{1,5}, {2,4}, {3, 6}, {4,1}, {5, 10}};

    Greedy(goods, 13);
    return 0;
}

你可能感兴趣的:(算法设计与分析,c++,开发语言,算法,贪心算法)