79647506

Date: 2025-06-01 12:15:48
Score: 0.5
Natty:
Report link

0/1 Knapsack Problem solved Mini

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, W;
    cout << "Enter number of items and knapsack capacity: ";
    cin >> n >> W;

    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];
    }

    // dp[w] = maximum value achievable with capacity w
    vector<int> dp(W + 1, 0);

    // Process each item
    for (int i = 0; i < n; i++) {
        // Traverse backwards to avoid reuse of same item multiple times
        for (int w = W; w >= weights[i]; w--) {
            dp[w] = max(dp[w], dp[w - weights[i]] + values[i]);
        }
    }

    cout << "Maximum value achievable: " << dp[W] << "\n";

    return 0;
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: user30687883