揹包 dp 雙重動態規劃

Raucous Rockers
“破鑼搖滾”樂隊
譯 by Maigo Akisame
你剛剛繼承了流行的“破鑼搖滾”樂隊錄製的尚未發表的N(1 <= N <= 20)首歌的版權。你打算從中精選一些歌曲,發行M(1 <= M <= 20)張CD。每一張CD最多可以容納T(1 <= T <= 20)分鐘的音樂,一首歌不能分裝在兩張CD中。

不巧你是一位古典音樂迷,不懂如何判定這些歌的藝術價值。於是你決定根據以下標準進行選擇:

歌曲必須按照創作的時間順序在CD盤上出現。
選中的歌曲數目儘可能地多。
PROGRAM NAME: rockers
INPUT FORMAT
第一行:   三個整數:N, T, M.  
第二行:   N個整數,分別表示每首歌的長度,按創作時間順序排列。  

SAMPLE INPUT (file rockers.in)
4 5 2
4 3 4 2
OUTPUT FORMAT
一個整數,表示可以裝進M張CD盤的樂曲的最大數目。
SAMPLE OUTPUT (file rockers.out)
3

 

 

 

分析:由於cd是按照時間順序的,而且每張碟的歌要比前一張碟出的晚,這就決定了可以把歌曲分成幾部分,分別裝入到cd中,有m張cd,則問題可描述成,把歌曲分堆,然後各自求最優裝載,分別用01揹包算法。由於不知道如何分堆纔會產生最優解,所以第一次動態規劃算出每個區間段的最優裝載,然後第二個動態規劃求出最優的分堆。這題可以用雙重動態規劃求解。

 

 

UASCO的標準解法跟有利於掌握動態規劃

分析:

能不能把當前的歌曲放入cd中,取決於一下三個條件:

1.目前cd中耗費的內存

2.當前歌曲長度

3. 最後一張放在cd中的歌曲(因爲題目要求歌曲要按時間順序放入cd)

dp時的維數和各維數的含義就從這裏得出

第一維是當前cd數

第二維是目前cd內存的耗費

第三維是最後放入的歌曲

以下是USACO的分析:

 

This is a pretty straight-forward dynamic programming problem. The factors that determine whether we can put a song on a CD are:

  • The length used up on the CD so far
  • The length of the current song
  • The last song that we put on the CD (because of the date restriction)

Therefore, we create an matrix called "dp", with dp[a][b][c] being the most number of songs that we can put on the first 'a' CDs, with 'b' minutes already used up on the 'a'th CD, and with 'c' being the last song that we put on CD 'a'. We initialize the matrix to be all zeroes, and then we cycle through it as follows:

  • We traverse the CDs in ascending order to satisfy the date requirement
  • We go through the number of minutes used in ascending order, so that we have had a chance to put on a song earlier in the CD before we try to put songs on at a later time
  • We go through the last song used in ascending order (although this order doesn't really matter)
  • We go through the new songs in ascending order, making sure to start with songs that were dated after the last song

If the new song that we want to include in the set will fit on the current CD, there is no reason to put it on the next CD, so we check the matrix and see if adding it to the current set of songs will be better than the value already stored in the matrix. Otherwise, we check to see if it would be beneficial to put the song on the next CD. As a time-saver, each time we check a current value in the matrix to see what other songs we can put on the CD, we also check and see if this value is better than the most number of CDs that we have currently been able to fit in the set, so that we don't need to do this at the end. Finally, we output this best number, which will be the most number of CDs that we can fit in the set.

 

發佈了20 篇原創文章 · 獲贊 8 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章