The last algorithmic dance

2019-09-06 01:14发布

问题:

[ Previous related question: A dance with an aglorithm's complexity ]

The story: I'm about to take part in a dance contest with n songs in a specific order. I can't dance to every single song, though, because I need time to prepare before each dance, and time to rest afterward. (Fortunately, the rest time from one dance can overlap with the preparation time for the next.)

I know what score I can get for each song I do dance to, and I want to maximize my total score.

So, I have three arrays:

  • score(i) is the score I can get for dancing to song #i.
  • prep(i) is the number of songs I have to skip immediately before song #i, or else I can't do song #i. (For example, if prep(4) = 2, then I can't dance to song #4 unless I've skipped both song #2 and song #3.)
  • rest(i) is the number of songs I have to skip immediately after song #i, if I did song #i. (For example, if rest(4) = 2, and I dance to song #4, then I have to skip both song #5 and song #6.)

Neither prep(i) nor rest(i) ever exceeds an upper bound, call it M.

How can I maximize my score? What's its complexity?


My attempt:

Based on the answer already given, take that

Opt(i) = max(Opt(i+1),
             Score(i) + Opt(i + 1 + rest(i))) for i = 0..n-1.

and build on it, so that we have as a dead time something like:

Opt(i + 1 + max(prep(i), rest(i)))

but I am worried, since i should descend, as mentioned in my linked question. Can anybody help please? That overlapping confuses me.

回答1:

# Get the first song that can be danced to assuming he danced to `i` and wanted to wait till prep time of a song
def myPrep(i):
    for j in range(i+1,n):
        if j - prep(j) > i:
            return j

for i in range(0,n-1):
    Opt(i) = max(Opt(i+1),
                 (Score(i) + Opt(i + 1 + rest(i))),
                 (Score(i) + Opt(i + 1 + myPrep(i)))
             )

In this case, I am thinking of three possibilities:

  • Skips current song -> Opt(i+1)
  • Dances to current song -> Score(i) and
    • waits for the resting period of ith song or
    • waits for the first song which provides enough prep time -> myPrep(i)

I debated with myself if I should include all the possible songs that have enough prep time after ith but then thought the Opt(myPrep(i)) should get the right number and hence we don't need to include all of the songs after myPrep(i) in calculation of ith song