charann29 / opensource

106 stars 245 forks source link

Run time error issue #617

Open namanmuktha opened 1 month ago

namanmuktha commented 1 month ago

I am experiencing a runtime error while solving knapsack2 problem from Atcoder Soln : https://github.com/namanmuktha/atcoderdp/blob/main/knapsacktabulation.cpp

charann29 commented 1 month ago

The runtime error in your code could be due to the use of the vector type for the w (weights) and p (profits) vectors while using vector<vector> for the dp table, where ll is a typedef for long long. If the input values for weights or profits are large, they might not fit into the int data type, causing issues when accessing elements.

#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;

int main() {
    ll n, W;
    cin >> n >> W;
    vector<ll> w(n); // Change int to ll
    vector<ll> p(n); // Change int to ll

    for (ll i = 0; i < n; i++) {
        cin >> w[i];
        cin >> p[i];
    }

    vector<vector<ll>> dp(n + 1, vector<ll>(W + 1, 0));

    for (ll i = 1; i <= n; i++) {
        for (ll j = 0; j <= W; j++) {
            ll nottaken = dp[i - 1][j];
            ll taken = -1e9;
            if (w[i - 1] <= j) {
                taken = dp[i - 1][j - w[i - 1]] + p[i - 1];
            }
            dp[i][j] = max(nottaken, taken);
        }
    }

    cout << dp[n][W] << endl;
    return 0;
}
charann29 commented 1 month ago

update me on this..