以下是使用 C++实现的贪心算法解决此问题的代码: ```cpp #include <iostream> #include <vector> #include <algorithm> // 结构体表示巧克力的价格和数量 struct Chocolate { int price; int quantity; }; // 比较函数,按照单位价格从低到高排序巧克力 bool compareChocolates(Chocolate a, Chocolate b) { return (double)a.price / a.quantity < (double)b.price / b.quantity; } int maxHappiness(int m, std::vector<Chocolate> chocolates) { // 对巧克力按照单位价格排序 std::sort(chocolates.begin(), chocolates.end(), compareChocolates); int happiness = 0; for (const auto& chocolate : chocolates) { // 计算可以购买的该种巧克力数量 int numBought = std::min(m / chocolate.price, chocolate.quantity); // 更新快乐值和剩余金额 happiness += numBought * 11; m -= numBought * chocolate.price; } return happiness; } int main() { std::vector<Chocolate> chocolates = { {10, 5}, {20, 3}, {30, 2} }; int m = 50; int happiness = maxHappiness(m, chocolates); std::cout << "最大快乐值: " << happiness << std::endl; return 0; } ``` 1. 注意输入的巧克力信息要准确,包括价格和数量。 2. 排序函数的比较逻辑要保证能正确按照单位价格排序。 3. 在计算可购买数量时,要考虑剩余金额和巧克力的库存数量。 [2024-12-20 19:15:35 | AI写代码神器 | 407点数解答]