Reputation: 151
I have been stuck on this problem. Can someone please help me solve this?
We are given n sorted lines of people with lengths l1, l2, ..., ln. The lines are all sorted by height. We want to merge all the lines into one sorted line. We can merge 2 lines at a time, which takes time that is proportional to the number of people in both lines.
Design an algorithm where we can choose the best order to merge all the lines for the least possible amount of time.
Upvotes: 2
Views: 141
Reputation: 4356
Consider the greedy algorithm:
while line number > 1:
take the shortest two lines li, lj
merge them
Is this the optimal solution? You see that the following facts are true:
You can implement this algorithm using min-priority queue.
initialize min-priority queue q
insert all line lengths in q
ans = 0
while q > 1:
a = q.pop()
b = q.pop()
ans += a+b
q.push(a+b)
return ans
Upvotes: 3