解决分数背包问题的C ++程序
在小背包问题中,给出了一组项目,每个项目都有一个权重和一个值。我们需要打破物品以最大化背包的总值,这可以通过贪婪的方法来完成。
算法
Begin Take an array of structure Item Declare value, weight, knapsack weight and density Calculate density=value/weight for each item Sorting the items array on the order of decreasing density We add values from the top of the array to total value until the bag is full, i.e; total value <= W End
范例程式码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef struct {
int v;
int w;
float d;
} Item;
void input(Item items[],int sizeOfItems) {
cout << "Enter total "<< sizeOfItems <<" item's values and weight" <<
endl;
for(int I = 0; I < sizeOfItems; i++) {
cout << "Enter "<< i+1 << " V ";
cin >> items[i].v;
cout << "Enter "<< i+1 << " W";
cin >> items[i].w;
}
}
void display(Item items[], int sizeOfItems) {
int i;
cout << "values: ";
for(i = 0; i < sizeOfItems; i++) {
cout << items[i].v << "\t";
}
cout << endl << "weight: ";
for (I = 0; I < sizeOfItems; i++) {
cout << items[i].w << "\t";
}
cout << endl;
}
bool compare(Item i1, Item i2) {
return (i1.d > i2.d);
}
float knapsack(Item items[], int sizeOfItems, int W) {
int i, j, pos;
Item mx, temp;
float totalValue = 0, totalWeight = 0;
for (i = 0; i < sizeOfItems; i++) {
items[i].d = items[i].v / items[i].w;
}
sort(items, items+sizeOfItems, compare);
for(i=0; i<sizeOfItems; i++) {
if(totalWeight + items[i].w<= W) {
totalValue += items[i].v ;
totalWeight += items[i].w;
} else {
int wt = W-totalWeight;
totalValue += (wt * items[i].d);
totalWeight += wt;
break;
}
}
cout << "total weight in bag " << totalWeight<<endl;
return totalValue;
}
int main() {
int W;
Item items[4];
input(items, 4);
cout << "Entered data \n";
display(items,4);
cout<< "Enter Knapsack weight \n";
cin >> W;
float mxVal = knapsack(items, 4, W);
cout << "Max value for "<< W <<" weight is "<< mxVal;
}输出结果
Enter total 4 item's values and weight Enter 1 V 50 Enter 1 W 10 Enter 2 V 60 Enter 2 W 20 Enter 3 V 70 Enter 3 W 30 Enter 4 V 70 Enter 4 W 40 Entered data values: 50 60 70 70 weight: 10 20 30 40 Enter Knapsack weight 60 total weight in bag 60 Max value for 60 weight is 180
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短