-1

What would be the solution to this problem? I think it would be rather tricky because you would have to juggle three characteristics.

Here is my attempt: p-value, s-weight, k-amount, max-maximum weight,

m-number of items to take

static int solution(int[] s, int[] p, int[] k, int max) {

        int[,] matrix = new int[s.Length + 1, max + 1];

        for (int i = 1; i <= s.Length; i++)
        {

            for (int j = 0; j <= max; j++)
            {                    

                int m = 1;
                for(int z = k[i - 1]; z > 0; z--)
                {
                    if(z * s[i - 1] <= j)
                    {                            
                        m = z;
                        break;

                    }
                }                    

                if (s[i - 1] * m <= j)
                {
                    matrix[i, j] =
                        Math.Max((p[i - 1] * m) + matrix[i - 1, j - s[i - 1] * m],
                    matrix[i - 1, j]);
                }
                else
                {
                    matrix[i, j] = matrix[i - 1, j];
                }

            }
        }

        return matrix[s.Length, max];
    }

2 Answers2

2

For knapsack with some amount of item copies there's a nice trick to reduce it to classical knapsack:

  1. Let's say we have x copies of some item weighting w and giving value v

  2. Notice that it's the same as having log x items where each item has w, 2*w, 4*w, ... weight and v, 2*v, 4*vvalue and sum of all weights is same as w*x

  3. In cases where x can't be expressed as sum of powers of 2 we can make last number what's left (i.e. if x=10, our weight distribution is: 1 + 2 + 4 + 3 = 10). The important thing is to choose such weights that all possible pickings of 1..x are possible to make by picking some subset

After this the problem is reduced to classical knapsack.

Complexity O(#items * #maxWeight * log2(#MaxItemCount)

Photon
  • 2,717
  • 1
  • 18
  • 22
0

We can make the dp matrix using the weight array and the amount array. For the amount array take the max of it (assume K), then make the dp matrix.

dp[n+1][k+1] gives the minimum cost to satisfy a person with capacity k who can eat the first n dishes (where n is the size of the weight array and k is the max amount a person can eat)

the relation afterward will be the same as an unbounded knapsack.

Pandapip1
  • 730
  • 5
  • 15
pp6669
  • 1