用一段代码来演示贪心算法
时间: 2023-03-30 21:00:20 浏览: 81
以下是一个使用贪心算法解决背包问题的示例代码:
#include <iostream>
#include <algorithm>
using namespace std;
struct Item {
int value;
int weight;
};
bool cmp(Item a, Item b) {
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}
double fractionalKnapsack(int W, Item arr[], int n) {
sort(arr, arr + n, cmp);
int curWeight = ;
double finalValue = .;
for (int i = ; i < n; i++) {
if (curWeight + arr[i].weight <= W) {
curWeight += arr[i].weight;
finalValue += arr[i].value;
} else {
int remain = W - curWeight;
finalValue += arr[i].value * ((double)remain / arr[i].weight);
break;
}
}
return finalValue;
}
int main() {
int W = 50;
Item arr[] = {{60, 10}, {100, 20}, {120, 30}};
int n = sizeof(arr) / sizeof(arr[]);
cout << "Maximum value we can obtain = "
<< fractionalKnapsack(W, arr, n);
return ;
}
这段代码演示了使用贪心算法解决背包问题,其中 Item 结构体表示物品的价值和重量,cmp 函数用于比较物品的单位价值,fractionalKnapsack 函数用于计算背包能够装下的最大价值。
阅读全文