Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <list>
- using namespace std;
- struct Thing {
- double cost;
- double weight;
- Thing(double cost, double weight) : cost(cost), weight(weight) { }
- friend bool operator==(const Thing& a, const Thing& b) {
- return a.cost == b.cost && a.weight == b.weight;
- }
- };
- class Backpack {
- public:
- Backpack(double limit) : limit_(limit), best_(0) { }
- list<Thing> enumeration(list<Thing>& things) {
- if (things.size() > 0) check(things);
- for (auto& thing : things) {
- auto tmp = list<Thing>(things);
- tmp.remove(thing);
- enumeration(tmp);
- }
- return things_;
- }
- private:
- double limit_;
- double best_;
- list<Thing> things_;
- double weight_(list<Thing>& things)const {
- auto sum = 0.0;
- for (auto& thing : things) sum += thing.weight;
- return sum;
- }
- double cost_(list<Thing>& things)const {
- auto sum = 0.0;
- for (auto& thing : things) sum += thing.cost;
- return sum;
- }
- void check(list<Thing>& things) {
- if (0 == things_.size()) {
- if (weight_(things) <= limit_) {
- things_ = things;
- best_ = cost_(things);
- }
- }
- else {
- if (weight_(things) <= limit_ && cost_(things) > best_) {
- things_ = things;
- best_ = cost_(things);
- }
- }
- }
- };
- list<Thing> input(unsigned quantity) {
- list<Thing> things;
- for (auto i = 0U; i < quantity; ++i) {
- cout << "Цена " << i + 1 << " предмета: ";
- double cost;
- cin >> cost;
- cout << "Вес " << i + 1 << " предмета: ";
- double weight;
- cin >> weight;
- things.emplace_back(Thing(cost, weight));
- }
- return things;
- }
- void show(list<Thing>& things) {
- auto weight = 0.0;
- auto cost = 0.0;
- for (auto& thing : things) {
- weight += thing.weight;
- cost += thing.cost;
- cout
- << "Вес: " << thing.weight
- << ", цена: " << thing.cost << '\n';
- }
- cout << "Общий вес: " << weight << ", сумма: " << cost << '\n';
- }
- int main() {
- setlocale(LC_CTYPE, "Russian");
- cout << "Введите предельный вес рюкзака: ";
- double weight;
- cin >> weight;
- Backpack backpack(weight);
- cout << "Введите количество предметов: ";
- unsigned quantity;
- cin >> quantity;
- auto things = input(quantity);
- auto result = backpack.enumeration(things);
- show(result);
- system("pause");
- }
Add Comment
Please, Sign In to add comment