Westonci.ca is the premier destination for reliable answers to your questions, brought to you by a community of experts. Join our Q&A platform to connect with experts dedicated to providing precise answers to your questions in different areas. Explore comprehensive solutions to your questions from a wide range of professionals on our user-friendly platform.

You are given a sequence of n songs where the ith song is l minutes long. You want to place all of the songs on an ordered series of CDs (e.g. CD 1, CD 2, CD 3,... ,CD k) where each CD can hold m minutes. Furthermore, (1) The songs must be recorded in the given order, song 1, song 2,..., song n. (2) All songs must be included. (3) No song may be split across CDs. Your goal is to determine how to place them on the CDs as to minimize the number of CDs needed. Give the most efficient algorithm you can to find an optimal solution for this problem, prove the algorithm is correct and analyze the time complexity

Sagot :

Answer:

This can be done by a greedy solution. The algorithm does the following:  

Put song 1 on CD1.

For song 1, if there's space left on the present CD, then put the song on the present CD. If not, use a replacement CD.

If there are not any CDs left, output "no solution".

Explanation:  

The main thing is prove the correctness, do that by the "greedy stays ahead argument". For the primary song, the greedy solution is perfect trivially.  

Now, let the optimal solution match the greedy solution upto song i. Then, if the present CD has space and optimal solution puts song (i+1) on an equivalent CD, then the greedy and optimal match, hence greedy is not any worse than the optimal.Else, optimal puts song (i + 1) on subsequent CD. Consider an answer during which only song (i + 1) is moved to the present CD and zip else is modified. Clearly this is often another valid solution and no worse than the optimal, hence greedy is not any worse than the optimal solution during this case either. This proves the correctness of the algorithm. As for every song, there are constantly many operations to try to do, the complexity is O(n).