C语言贪心法:巧妙解决背包问题,实现价值最大化
```c #include <stdio.h> // 定义一个结构体来存储物品的信息 typedef struct { int weight; int value; int index; } Item; // 比较函数,用于排序 int compare(const void *a, const void *b) { Item *itemA = (Item *)a; Item *itemB = (Item *)b; // 按照单位价值从高到低排序 return (itemB->value / itemB->weight) - (itemA->value / itemA->weight); } int main() { int n; // 物品数量 scanf("%d", &n); Item items[n]; for (int i = 0; i < n; i++) { scanf("%d", &items[i].weight); items[i].index = i + 1; } for (int i = 0; i < n; i++) { scanf("%d", &items[i].value); } int capacity; // 背包容量 scanf("%d", &capacity); // 按照单位价值从高到低排序 qsort(items, n, sizeof(Item), compare); int totalWeight = 0; int totalValue = 0; int selectedItems[100]; // 存储选择的物品索引 int selectedItemCount = 0; // 选择物品 for (int i = 0; i < n; i++) { if (totalWeight + items[i].weight <= capacity) { totalWeight += items[i].weight; totalValue += items[i].value; selectedItems[selectedItemCount++] = items[i].index; } } // 输出结果 printf("选择物品: "); for (int i = 0; i < selectedItemCount; i++) { printf("%d ", selectedItems[i]); } printf("\n总重量: %d\n总价值: %d\n", totalWeight, totalValue); return 0; } ``` ### 需要注意的逻辑点: 1. **单位价值计算**:在排序时,按单位价值(即价值除以重量)从高到低排序,确保优先选择单位价值高的物品。 2. **容量限制**:在选择物品时,要确保当前选择的物品不会超过背包的容量。 3. **选择记录**:记录选择的物品索引,以便输出最终选择的物品列表。 ######[AI写代码神器 | 539点数解答 | 2024-11-27 08:36:20]
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)343
- C3期末:精准求解 3 - 20 范围内数列第 k 项值及注意要点(字节豆包 | 242点数解答 | 2025-06-15 11:26:19)135
- C++求解:查找3 - 20项数列第k项值及注意要点(字节豆包 | 325点数解答 | 2025-06-15 11:27:11)154
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)310
- C++ 破解“没有 3 的世界”:找出第 n 个特殊正整数!(字节豆包 | 333点数解答 | 2025-03-17 22:48:43)150
- 破解Jenkins构建Java项目“数据收集等待过长”难题的实用攻略( | 389点数解答 | 2024-01-18 09:27:30)328
- Jenkins 构建 Java 项目“数据收集等待过长”难题的 10 大解决策略(百度文心 | 551点数解答 | 2024-01-18 09:27:54)289
- C++ 求解整数减少至 0 使奇数次数最少的最小纠结次数问题(字节豆包 | 229点数解答 | 2024-08-21 16:33:58)259
- C++ 实现按复杂规则计算业务员工资,附完整代码!(字节豆包 | 337点数解答 | 2024-11-18 17:48:36)284
- C++ 实现:求解二进制字符串中消除连续 m 个 0 的最少操作次数(GPT | 876点数解答 | 2024-11-30 23:07:54)211
- 奇幻游戏积分排序:奇数升序偶数降序,Python代码轻松搞定!(DeepSeek | 233点数解答 | 2025-04-12 17:08:17)210
- C++实现奇幻游戏积分排序:奇数升序偶数降序!(DeepSeek | 237点数解答 | 2025-04-12 17:09:06)229