Solution: The problem is very similar to the 0-1 knapsack. We can also use similar strategy to solve it. The detail is as follow:
- Basically, we need first sort different types of freight by their weight.
- Then we will need to fill an array dp[n][W+1] where n is the number of different types of freights. dp[i][j] represents the minmum cost to throw out at least j lbs freight and we can throw up to ith type of freights (ranked by their unit weight and from light to heavy).
- To fill dp[i][j],
we need first select the most cost/efficient type of freight among the i types of freights. Cost/efficient is measured by the unit weight of the freight divided by its unit price. Say the most cost/efficient type of freight among the i types of freights is kth type of freights, we have if j <= kth type's unit weight, dp[i][j] = min(dp[i-1][j], kth type's unit price); Otherwise, dp[i][j] = min(dp[i-1][j], dp[i][j-kth type's unit weight] + kth type's unit price).We don't need to use greedy method, just do regular dp. - The time complexity of this approach is O(nW).
No comments:
Post a Comment