mercredi 27 mai 2020

Knapstack implementation in c++ using memoization

What is the difference between doing int t[102][1002] = {-1}; vs running a for loop and doing

for(int i = 0; i < 102; i++)
        for(int j = 0; j < 1002; j++)
            t[i][j] = -1;

The code below does not work when the former method is used. It works only when we I loop through and initialize. Why is that?

#include<bits/stdc++.h>
using namespace std;
int t[102][1002] = {-1};
int knapstack(int wt[], int val[], int w, int n)
{
    if(n == 0 || w == 0)
        return 0;

    if (t[n][w] != -1)
        return t[n][w];

    if(wt[n-1] <= w ){
        t[n][w] = max(val[n-1] + knapstack(wt,val, w - wt[n-1],n-1) , knapstack(wt, val, w, n-1));
        return t[n][w];
    }

    if(wt[n-1] > w){
       t[n][w] = knapstack(wt,val,w,n-1); 
       return t[n][w];
    }
}

int main()
{
    int wt[] = {10, 20, 30};
    int val[] = { 60, 100, 120};
    int w = 50, n = sizeof(val)/sizeof(val[0]);
    cout<< knapstack(wt, val, w, n);
}

Aucun commentaire:

Enregistrer un commentaire