【发布时间】:2021-07-08 13:27:25
【问题描述】:
我提供的是分数背包问题的解决方案的完整代码。在代码的最后我会解释问题,
#include<iostream>
#include<queue>
#define MAX_WEIGHT 5
using namespace std;
class Item{
public:
int weight;
int benefit;
float weightPerBenefit;
int selectedWeight = 0;
Item(int weight, int benefit){
this->weight = weight;
this->benefit = benefit;
this->weightPerBenefit = (float)this->weight/(float)this->benefit;
}
void setSelectedWeight(int w){
this->selectedWeight = w;
}
bool operator < (const Item &item) const{
return weightPerBenefit < item.weightPerBenefit;
}
};
void displayItems(priority_queue<Item> items){
while(!items.empty()){
Item item = items.top();
items.pop();
cout << "Item Benefit: " << item.benefit << ", Selected Weight: " << item.selectedWeight << endl;;
}
}
void fractionalKnapsack(priority_queue<Item> items){
int rw = MAX_WEIGHT;
while(!items.empty()){
Item item = items.top();
items.pop();
int w = item.weight;
if(w > rw){
item.setSelectedWeight(rw);
break;
}
else{
//cout << w << endl;
item.setSelectedWeight(w);
rw = rw-w;
}
}
}
int main(){
int size;
cout << "Enter total number of items: ";
cin >> size;
priority_queue<Item> items;
int data[size][2];
for(int i=0; i<size; i++){
cout << "Enter item weight: ";
cin >> data[i][0];
cout << "Enter item benefit: ";
cin >> data[i][1];
cout << endl;
}
for(int i=0; i<size; i++){
Item item(data[i][0], data[i][1]);
items.push(item);
}
//displayItems(items);
fractionalKnapsack(items);
displayItems(items);
}
所以,问题是每当调用fractionalKnapsack 函数并更新对象的属性时,在显示方法之后它会显示在开始时定义的属性值0。它不会更新为新值。
我对priority_queue不太了解,必须使用优先队列来完成。我不知道为什么会发生这个错误。
【问题讨论】:
-
fractionalKnapsack清空队列的副本,保持原件不变。而且无论如何也无法修改priority_queue中的元素。 -
另外,贪心算法是“尽可能多地取‘最好’的项目,然后是第二好的,以此类推”。这不需要对元素进行任何修改 - 只需弹出它们直到你的背包装满或用完东西。
-
当您决定将结果存储在与输入相同的位置时,我认为您走错了方向。
标签: c++ priority-queue