Reputation: 172
I'm trying to solve following knapsack problem with two constrains.
What we know:
Constrains:
Can anyone give me some advice about algorithm i should use, pseudo code or good article?
UPDATE:
Important thing I forgot to mention is that I also need to know which items I putted in the bag.
Upvotes: 0
Views: 10204
Reputation: 3
Non-recursive approach
# N: number of items, W: max weight of knapsack, F: max amount of fragile items
# if item doesn't fit, then skip
# if it fits, check if it's worth to take it
dp[N+1][W+1][F+1] # filled with zeros
benefit, weight, fragility = [] # arrays filled with respective item properties
for n in range(1, N + 1):
for w in range(1, W + 1):
for f in range(0, F + 1):
if weight[n-1] > w or fragility[n-1] > f:
dp[n][w][f] = dp[n-1][w][f]
else:
dp[n][w][f] = max(dp[n-1][w][f],
dp[n-1][w-weight[n-1]][f-fragility[n-1]] + benefit[n-1])
print(dp[N][W][F]) # prints optimal knapsack value
Listing items
knapsack = [] # indexes of picked items
n = N
w = W
f = F
while n > 0:
if dp[n][w][f] != dp[n-1][w][f]:
knapsack.append(n-1)
w -= weight[n-1]
f -= fragility[n-1]
n -= 1
print(knapsack) # prints item indexes
Upvotes: 0
Reputation: 2777
It looks like a modification to knapsack would solve it.
Let's say we have N items, maximum knapscak weight is W, and max amount of fragile items is F
let's define our dp table as 3-dimensional array dp[N+1][W+1][F+1]
Now dp[n][w][f] stores maximum value we can get if we fill knapsack with some subset of items from first n items, having weight of exacly w and having exacly f fragile items.
frop dp[n][w][f] we can move to states:
so pseudocde:
dp[N+1][W+1][F+1] // memo table, initially filled with -1
int solve(n,w,f)
{
if(n > N)return 0;
if(dp[n][w][f] != -1) return dp[n][w][f];
dp[n][w][f] = solve(n+1,w,f); //skip item
if(w + weight(n) <= W && f + isFragile(n) <=F)
dp[n][w][f] = max(dp[n][w][f], value(n) + solve(n+1, w + weight(n), f + isFragile(n)));
return dp[n][w][f]
}
print(solve(1,0,0))
Getting the actual subset is also not difficult:
vector<int> getSolution(n,w,f)
{
int optimalValue = solve(n,w,f);
vector<int>answer; //just some dynamic array / arrayList
while(n <= N)
{
if(solve(n+1,w,f) == optimalValue)n++; //if after skipping item we can still get optimal answer we just skip it
else //otherwise we cant so current item must be taken
{
int new_w = w + weight(n);
int new_f = f + isFragile(n);
answer.push_back(n); //so we just save its index, and update all values
optimalValue -= value(n);
n++;
w = new_w;
f = new_f;
}
}
return answer;
}
Upvotes: 1