build
This commit is contained in:
parent
02757deee2
commit
5f22f10c68
@ -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"
|
||||
|
@ -346,7 +346,27 @@ $$
|
||||
=== "C"
|
||||
|
||||
```c title="max_capacity.c"
|
||||
[class]{}-[func]{maxCapacity}
|
||||
/* 最大容量:贪心 */
|
||||
int maxCapacity(int ht[], int htLength) {
|
||||
// 初始化 i, j 分列数组两端
|
||||
int i = 0;
|
||||
int j = htLength - 1;
|
||||
// 初始最大容量为 0
|
||||
int res = 0;
|
||||
// 循环贪心选择,直至两板相遇
|
||||
while (i < j) {
|
||||
// 更新最大容量
|
||||
int capacity = MIN(ht[i], ht[j]) * (j - i);
|
||||
res = MAX(res, capacity);
|
||||
// 向内移动短板
|
||||
if (ht[i] < ht[j]) {
|
||||
i++;
|
||||
} else {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
@ -322,7 +322,26 @@ $$
|
||||
=== "C"
|
||||
|
||||
```c title="max_product_cutting.c"
|
||||
[class]{}-[func]{maxProductCutting}
|
||||
/* 最大切分乘积:贪心 */
|
||||
int maxProductCutting(int n) {
|
||||
// 当 n <= 3 时,必须切分出一个 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
int a = n / 3;
|
||||
int b = n % 3;
|
||||
if (b == 1) {
|
||||
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b == 2) {
|
||||
// 当余数为 2 时,不做处理
|
||||
return pow(3, a) * 2;
|
||||
}
|
||||
// 当余数为 0 时,不做处理
|
||||
return pow(3, a);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
@ -1,5 +1,5 @@
|
||||
{% if page.meta.comments %}
|
||||
<h5 align="center" id="__comments">{{ "欢迎你提出疑问或建议" }}</h5>
|
||||
<h5 align="center" id="__comments">{{ "欢迎在评论区提出疑问或建议" }}</h5>
|
||||
<!-- Insert generated snippet here -->
|
||||
<script
|
||||
src="https://giscus.app/client.js"
|
||||
|
Loading…
Reference in New Issue
Block a user