diff --git a/chapter_greedy/fractional_knapsack_problem.md b/chapter_greedy/fractional_knapsack_problem.md index 5e062e289..55d2add1d 100644 --- a/chapter_greedy/fractional_knapsack_problem.md +++ b/chapter_greedy/fractional_knapsack_problem.md @@ -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" diff --git a/chapter_greedy/max_capacity_problem.md b/chapter_greedy/max_capacity_problem.md index b25b37b30..6443ad17f 100644 --- a/chapter_greedy/max_capacity_problem.md +++ b/chapter_greedy/max_capacity_problem.md @@ -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" diff --git a/chapter_greedy/max_product_cutting_problem.md b/chapter_greedy/max_product_cutting_problem.md index 490ae65a0..d831433bc 100644 --- a/chapter_greedy/max_product_cutting_problem.md +++ b/chapter_greedy/max_product_cutting_problem.md @@ -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" diff --git a/overrides/partials/comments.html b/overrides/partials/comments.html index 93ec2b2dd..6b2953ca7 100755 --- a/overrides/partials/comments.html +++ b/overrides/partials/comments.html @@ -1,5 +1,5 @@ {% if page.meta.comments %} -
{{ "欢迎你提出疑问或建议" }}
+
{{ "欢迎在评论区提出疑问或建议" }}