请精修这段代码#include <iostream>#include <vector>#include <algorithm>using namespace std;struct item { int weight; int value;};bool cmp(item i1, item i2) { return i1.value * i2.weight > i2.value * i1.weight;}pair<int, vector<int>> knapsack(vector<item>& items, int capacity) { int n = items.size(); vector<int> selected_items(n, 0); int total_value = 0; sort(items.begin(), items.end(), cmp); for (int i = 0; i < n; i++) { if (capacity == 0) break; if (items[i].weight <= capacity) { selected_items[i] = 1; total_value += items[i].value; capacity -= items[i].weight; } else { selected_items[i] = capacity / items[i].weight; total_value += selected_items[i] * items[i].value; capacity -= selected_items[i] * items[i].weight; } } return make_pair(total_value, selected_items);}int main() { vector<item> items = {{2, 10}, {3, 15}, {5, 20}}; int capacity = 8; auto result = knapsack(items, capacity); cout << "Total value: " << result.first << endl; cout << "Selected items: "; for (int i : result.second) { cout << i << " "; } cout << endl; return 0;}
时间: 2024-03-05 10:50:11 浏览: 137
#include <iostream> #include<iomanip> using namespace std;九九乘法表
这段代码已经很精简了,但还是可以做一些微调,以下是我建议的改进:
1. 将头文件的顺序改为先算法库再是标准库,遵循头文件依赖关系原则。
2. 结构体 item 可以使用 class 替代,同时将结构体内部的成员变量声明为 private,提高代码的封装性。
3. 为结构体 item 添加构造函数,以便在创建对象时同时初始化成员变量。
4. 在 knapsack 函数中,使用 auto& 而不是 auto 来避免进行不必要的拷贝操作。
5. 在 for 循环中,使用 auto& 而不是 auto 来避免进行不必要的拷贝操作。
6. 将 make_pair 改为 { },可以使代码更加简洁。
修改后代码如下:
```
#include <algorithm>
#include <vector>
#include <iostream>
using std::vector;
using std::cout;
using std::endl;
class Item {
public:
Item(int w, int v) : weight(w), value(v) {}
int getWeight() const { return weight; }
int getValue() const { return value; }
private:
int weight;
int value;
};
bool cmp(const Item& i1, const Item& i2) {
return i1.getValue() * i2.getWeight() > i2.getValue() * i1.getWeight();
}
std::pair<int, vector<int>> knapsack(vector<Item>& items, int capacity) {
int n = items.size();
vector<int> selected_items(n, 0);
int total_value = 0;
std::sort(items.begin(), items.end(), cmp);
for (auto& item : items) {
if (capacity == 0) break;
if (item.getWeight() <= capacity) {
selected_items.push_back(1);
total_value += item.getValue();
capacity -= item.getWeight();
} else {
selected_items.push_back(capacity / item.getWeight());
total_value += selected_items.back() * item.getValue();
capacity -= selected_items.back() * item.getWeight();
}
}
return { total_value, selected_items };
}
int main() {
vector<Item> items = { {2, 10}, {3, 15}, {5, 20} };
int capacity = 8;
auto& result = knapsack(items, capacity);
cout << "Total value: " << result.first << endl;
cout << "Selected items: ";
for (auto& i : result.second) {
cout << i << " ";
}
cout << endl;
return 0;
}
```
阅读全文