[Coding Made Simple] Cutting Rod for max profit

本文探讨了如何通过动态规划解决杆切割问题以最大化利润。给出了一种算法实现方案,并详细解释了状态转移方程。此外,还提供了一个用于确定最佳切割方案的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a rod of length and prices at which different length of this rod can sell, how do you cut this rod to maximize profit.

 

Solution. Dynamic Programming

State: T[i][j]: the max profit when the rod's length is j and the first i cutting methods are available. 

Function: T[i][j] = max{T[i - 1][j],  entries[i - 1].profit + T[i][j - entries[i - 1].len]},   if j >= entries[i - 1].len;

     T[i][j] = T[i - 1][j], if j < entries[i - 1].len;

For a given cutting method of certain length and profit, we can only use this method when the current rod's length is at least as long as the cut length.

1. If the current rod's length is shorter than the cut length, then the max profit we can have is simply the same rod's length without using this cut length at all. 

2. Otherwise, the max profit is the max of either not using the current cut length or using it. 

 

 1 import java.util.ArrayList;
 2 
 3 class LenAndProfit {
 4     int len;
 5     int profit;
 6     LenAndProfit(int l, int p) {
 7         this.len = l;
 8         this.profit = p;
 9     }
10 }
11 public class CuttingRod {
12     private ArrayList<Integer> cuts;
13     public int getMaxProfit(int totalLen, LenAndProfit[] entries) {
14         int[][] T = new int[entries.length + 1][totalLen + 1];
15         for(int i = 0; i <= entries.length; i++) {
16             T[i][0] = 0;
17         }
18         for(int j = 0; j <= totalLen; j++) {
19             T[0][j] = 0;
20         }
21         for(int i = 1; i < T.length; i++) {
22             for(int j = 1; j <= totalLen; j++) {
23                 if(j >= entries[i - 1].len) {
24                     T[i][j] = Math.max(T[i - 1][j], entries[i - 1].profit + T[i][j - entries[i - 1].len]);
25                 }
26                 else {
27                     T[i][j] = T[i - 1][j];
28                 }
29             }
30         }
31         cuts = getMaxProfitCut(T, entries);
32         return T[entries.length][totalLen];
33     }
34     private ArrayList<Integer> getMaxProfitCut(int[][] T, LenAndProfit[] entries) {
35         ArrayList<Integer> cuts = new ArrayList<Integer>();
36         int i = T.length - 1, j = T[0].length - 1;
37         while(T[i][j] != 0) {
38             if(T[i - 1][j] == T[i][j]) {
39                 i--;
40             }
41             else {
42                 cuts.add(entries[i - 1].len);
43                 j -= entries[i - 1].len;
44             }
45         }
46         return cuts;
47     }
48 }

 

Related Problems

BackPack

转载于:https://www.cnblogs.com/lz87/p/7288813.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值