|
|
|
@ -428,9 +428,40 @@ status: new
|
|
|
|
|
=== "C"
|
|
|
|
|
|
|
|
|
|
```c title="fractional_knapsack.c"
|
|
|
|
|
[class]{Item}-[func]{}
|
|
|
|
|
/* 物品 */
|
|
|
|
|
struct Item {
|
|
|
|
|
int w; // 物品重量
|
|
|
|
|
int v; // 物品价值
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
[class]{}-[func]{fractionalKnapsack}
|
|
|
|
|
typedef struct Item Item;
|
|
|
|
|
|
|
|
|
|
/* 分数背包:贪心 */
|
|
|
|
|
float fractionalKnapsack(int wgt[], int val[], int itemCount, int cap) {
|
|
|
|
|
// 创建物品列表,包含两个属性:重量、价值
|
|
|
|
|
Item *items = malloc(sizeof(Item) * itemCount);
|
|
|
|
|
for (int i = 0; i < itemCount; i++) {
|
|
|
|
|
items[i] = (Item){.w = wgt[i], .v = val[i]};
|
|
|
|
|
}
|
|
|
|
|
// 按照单位价值 item.v / item.w 从高到低进行排序
|
|
|
|
|
qsort(items, (size_t)itemCount, sizeof(Item), sortByValueDensity);
|
|
|
|
|
// 循环贪心选择
|
|
|
|
|
float res = 0.0;
|
|
|
|
|
for (int i = 0; i < itemCount; i++) {
|
|
|
|
|
if (items[i].w <= cap) {
|
|
|
|
|
// 若剩余容量充足,则将当前物品整个装进背包
|
|
|
|
|
res += items[i].v;
|
|
|
|
|
cap -= items[i].w;
|
|
|
|
|
} else {
|
|
|
|
|
// 若剩余容量不足,则将当前物品的一部分装进背包
|
|
|
|
|
res += (float)cap / items[i].w * items[i].v;
|
|
|
|
|
cap = 0;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
free(items);
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
=== "Zig"
|
|
|
|
|