Arnhav's Cake Problem (Hard Version) Editorial

Abstract:

It was the harder version of the problem ACPE in the same contest. It again involves the use of greedy algorithm to maximise profit. But the constraints are higher this time and the **O(n.k)** solution for ACPE will produce TLE. Here we make use of priority queue to select jobs of highest profit from last day onwards.

Brief Solution:

For each day, list the jobs whose deadline is on that day.

Create a priority queue Q and starting from last day, add all jobs listed on that day to Q.

For each day, until more jobs can be done on that day or Q becomes empty, add the profit of the top job to total profit and remove top element of Q.

Then move onto the previous day and continue till day one.

MAX-PROFIT(jobs,days)

- for i from 1 to jobs.size
- days[jobs[i].deadline].job_list.add(jobs[i]) //add the job to the list in its deadline
- priority_queue Q
- for i from days.size till 1
- for j from 1 to days[i].job_list.size()
`Q.add(days[i].job_list[j]) // add all the jobs on day i to Q`

- for i from 1 to days[i].job_num
`if(Q is not empty)`

`total+=Q.front.profit`

`Q.remove(Q.front)`

- else break

12.return total

Time-Complexity:

- Line 1 and 2 - creating list for every day: O(k)
- Adding one job to Q: O(log k)
- Adding every job to Q: O(k log k)
- Line 5 and 6 - checking for everyday and adding every job to Q: O(n + klogk)
- Removing one job from Q - O(log k)
- Line 7 to 11 - checking for everyday and removing every job from Q: O(n + klogk)

**Overall:**O(n + klogk)