C/C++

Программирование c++. Помогите в написании кода!

Задание представлено на фото!
капец ты же знаешь что это классическая нп-полная проблема у которой в лучшем случае есть динамиское решение. Такое задают на 3 курсе компьютер саенса.

банальный вопрос банальный ответ я попросил чатжопати сгенерить

can you suggest a c++ code to solve a knapsack problem in case when we have infinite copies of each object with weight and value?

Certainly! When you have infinite copies of each object in the knapsack problem, it's referred to as the "Unbounded Knapsack" problem. Here's a C++ code to solve the Unbounded Knapsack problem using dynamic programming:


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int unboundedKnapsack(int capacity, const vector<int>& weights, const vector<int>& values) {
int n = weights.size();
vector<int> dp(capacity + 1, 0);

for (int i = 0; i <= capacity; i++) {
for (int j = 0; j < n; j++) {
if (weights[j] <= i) {
dp[i] = max(dp[i], dp[i - weights[j]] + values[j]);
}
}
}

return dp[capacity];
}

int main() {
int capacity, n;
cout << "Enter the knapsack capacity: ";
cin >> capacity;

cout << "Enter the number of items: ";
cin >> n;

vector<int> weights(n), values(n);
cout << "Enter weight and value of each item:\n";
for (int i = 0; i < n; i++) {
cin >> weights[i] >> values[i];
}

int maxTotalValue = unboundedKnapsack(capacity, weights, values);
cout << "The maximum total value that can be obtained is: " << maxTotalValue << endl;

return 0;
}
In this code, we use dynamic programming to find the maximum total value that can be obtained with the given knapsack capacity, weights, and values. The unboundedKnapsack function calculates the maximum value using a 1D array dp, where dp[i] represents the maximum value achievable with a knapsack of capacity i.

The outer loop iterates over all possible capacities from 0 to the given capacity, and the inner loop iterates over all items. If the weight of the current item is less than or equal to the current capacity, we check if adding the current item gives us a better value than the previously calculated value. If it does, we update dp[i] accordingly.

Finally, the unboundedKnapsack function returns the maximum value that can be achieved with the given knapsack capacity.
Петр Смолин
Петр Смолин
17 648
никита негатив