[英]Knapsack constraint python
假設我有一個代表籃球運動員的元組列表,以及他們的姓名,位置,費用和預計得分,
listOfPlayers = [
("Player1","PG",Cost,projectedPoints),
("Player2","PG",Cost,projectedPoints),
("Player3","SG",Cost,projectedPoints),
("Player4","SG",Cost,projectedPoints),
("Player5","SF",Cost,projectedPoints),
("Player6","SF",Cost,projectedPoints),
("Player7","PF",Cost,projectedPoints),
("Player8","PF",Cost,projectedPoints),
("Player9","C",Cost,projectedPoints),
("Player10","C",Cost,projectedPoints)
]
假設所有名稱,成本和預計點都是可變的。
我有一個傳統的背包問題,他們可以根據給定的重量對背包進行分類和包裝。 但是,這並不說明職位。
我想知道是否有一種方法可以編輯背包代碼,使其僅包含每個位置之一,即(pg,sg,sf,pf,c)。
傳統的0/1背包可以做到這一點,還是我需要切換到其他東西?
這稱為“多項選擇背包問題”。
您可以使用類似於動態編程解決方案的算法來解決0/1背包問題。
0/1背包問題的解決方案如下:(來自Wikipedia )
將
m[i, w]
定義為重量小於或等於w
使用i
項可獲得的最大值。
我們可以遞歸定義m[i, w]
如下:m[i, w] = m[i-1, w] if w_i > w (new item is more than current weight limit) m[i, w] = max(m[i-1, w], m[i-1, w-w_i] + v_i) if w_i <= w.
然后可以通過計算
m[n,W]
找到解決方案。 為了有效地做到這一點,我們可以使用一個表來存儲以前的計算。
現在,擴展名只是查找所有選擇中的最大值。
對於n
位置i
可供選擇的玩家( c_i_j
是選擇j
的成本, p_i_j
是積分),我們將有:
m[i, c] = max(m[i-1, c],
m[i-1, c-c_i_1] + p_i_1 if c_i_1 <= c, otherwise 0,
m[i-1, c-c_i_2] + p_i_2 if c_i_2 <= c, otherwise 0,
...
m[i-1, c-c_i_n] + p_i_n if c_i_n <= c, otherwise 0)
所以,說我們有:
Name Position Cost Points
Player1 PG 15 5
Player2 PG 20 10
Player3 SG 9 7
Player4 SG 8 6
然后,我們將有2個職位“ PG”和“ SG”,每個職位將有2個選擇。
因此,對於位置“ PG”(在i=1
),我們將有:
m[i, c] = max(m[i-1, c],
m[i-1, c-15] + 5 if 15 <= c, otherwise 0,
m[i-1, c-20] + 10 if 20 <= c, otherwise 0)
對於位置“ SG”(在i=2
),我們將有:
m[i, c] = max(m[i-1, c],
m[i-1, c-9] + 7 if 9 <= c, otherwise 0,
m[i-1, c-8] + 6 if 8 <= c, otherwise 0)
首先,達克林的出色回答。 我沒有發表評論的特權,所以我正在寫答案。 這實際上是一個“多選擇背包問題”。 我實現了其中一種問題,並在Online Judge中成功運行了該問題。 杜克林算法的唯一問題是,它不會考慮先前項目集中的至少一項。 因此,從上面:
m[i, c] = max(m[i-1, c],
m[i-1, c-15] + 5 if 15 <= c, otherwise 0,
m[i-1, c-20] + 10 if 20 <= c, otherwise 0)`
這最多只適用於一種。 如果您為零添加一點校驗,那么對於i=1
(“ PG”)而言,它恰好適合每種類型的一項:
m[i, c] = max(m[i-1, c],
m[i-1, c-15] + 5 if 15 <= c and m[i-1, c-15] != 0, otherwise 0,
m[i-1, c-20] + 10 if 20 <= c and m[i-1, c-20] != 0, otherwise 0)
對於i=2
(“ SG”):
m[i, c] = max(m[i-1, c],
m[i-1, c-9] + 7 if 9 <= c and m[i-1, c-9] != 0, otherwise 0,
m[i-1, c-8] + 6 if 8 <= c and m[i-1, c-8] != 0, otherwise 0)
等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.