Advertisement
Dimaush

Untitled

Dec 24th, 2022
1,142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class TBag {
  5. private:
  6.     unsigned amount;
  7.     unsigned capacity;
  8.     std::vector<unsigned> mass;
  9.     std::vector<unsigned> cost;
  10.     std::vector<std::vector<unsigned>> total_cost;
  11.  
  12. public:
  13.     TBag(unsigned a, unsigned c) : amount(a), capacity(c), mass(amount), cost(amount), total_cost(amount + 1, std::vector<unsigned>(capacity + 1)) {}
  14.  
  15.     void ReadFromStream(std::istream& stream) {
  16.         for (auto iter = mass.begin(); iter != mass.end(); ++iter) {
  17.             stream >> *iter;
  18.         }
  19.         for (auto iter = cost.begin(); iter != cost.end(); ++iter) {
  20.             stream >> *iter;
  21.         }
  22.     }
  23.  
  24.     void Fill() {
  25.         for (unsigned i = 0; i <= amount; ++i) {
  26.             total_cost[i][0] = 0;
  27.         }
  28.         for (unsigned j = 0; j <= capacity; ++j) {
  29.             total_cost[0][j] = 0;
  30.         }
  31.         for (unsigned i = 1; i <= amount; ++i) {
  32.             for (unsigned j = 1; j <= capacity; ++j) {
  33.                 if (j >= mass[i - 1]) {
  34.                     total_cost[i][j] = std::max(total_cost[i - 1][j], total_cost[i - 1][j - mass[i - 1]] + cost[i - 1]);
  35.                 } else {
  36.                     total_cost[i][j] = total_cost[i - 1][j];
  37.                 }
  38.             }
  39.         }
  40.     }
  41.  
  42.     unsigned MaxValue() {
  43.         Fill();
  44.         return total_cost[amount][capacity];
  45.     }
  46. };
  47.  
  48. TBag create(std::istream& stream) {
  49.     unsigned n, m;
  50.     stream >> n >> m;
  51.     TBag t(n, m);
  52.     t.ReadFromStream(stream);
  53.     return t;
  54. }
  55.  
  56. int main() {
  57.     TBag b = create(std::cin);
  58.     std::cout << b.MaxValue() << std::endl;
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement