Editorial for Deadline Homework
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Each assignment takes exactly one hour, so by time you can finish at most
assignments.
Sort the assignments by deadline. As you scan them in that order, keep a min-heap containing the scores of the assignments you currently plan to do.
When you see an assignment with score :
- Add
to the heap.
- If the heap now contains more than
assignments, remove the smallest score.
Why is this correct? After processing all assignments with deadline at most , any valid plan
can contain at most
of them. If we currently have too many chosen assignments, removing the
smallest score is always optimal, since it keeps the total score as large as possible.
At the end, the heap contains exactly the set of assignments in an optimal schedule, so the answer is the sum of its scores.
This runs in time.
Solution (Python)
import heapq
n = int(input())
assignments = [tuple(map(int, input().split())) for _ in range(n)]
assignments.sort()
chosen = []
total = 0
for deadline, score in assignments:
heapq.heappush(chosen, score)
total += score
if len(chosen) > deadline:
total -= heapq.heappop(chosen)
print(total)
Comments