Timed Cost Element Manager Solution
Problem Statement
Implement a data structure, `TimedCostElementManager`, that efficiently manages elements, each characterized by a positive integer `deadline` and a positive integer `cost`. The data structure must support the following two operations: 1. `add(deadline, cost)`: Adds a new element with the given `deadline` and `cost` to the manager. 2. `process()`: Removes and returns the element that has the highest priority. The priority is determined first by the earliest `deadline`. If multiple elements share the same earliest `deadline`, then the element with the lowest `cost` has higher priority. If the manager is empty, `process()` should return `(-1, -1)`. Your implementation should ensure that both `add` and `process` operations are highly efficient.
Examples
Constraints
- `1 <= deadline, cost <= 10^9`
- `1 <= Total number of operations (add or process) <= 10^5`
- Both `add` and `process` operations should have an average time complexity of `O(log N)`, where `N` is the number of elements currently in the manager.
- The system should correctly handle duplicate `(deadline, cost)` pairs.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import heapq
import sys
class TimedCostElementManager:
def __init__(self):
# The heap will store tuples (deadline, cost).
# Python's default tuple comparison works as desired:
# It compares elements from left to right.
# So (d1, c1) < (d2, c2) means d1 < d2, or d1 == d2 and c1 < c2.
self.priority_queue = []
def add(self, deadline: int, cost: int) -> None:
heapq.heappush(self.priority_queue, (deadline, cost))
def process(self) -> tuple[int, int]:
if not self.priority_queue:
return (-1, -1)
return heapq.heappop(self.priority_queue)
# Driver code
def main():
manager = TimedCostElementManager()
# Read the number of operations
num_operations = int(sys.stdin.readline())
for _ in range(num_operations):
line = sys.stdin.readline().split()
command = line[0]
if command == 'add':
deadline = int(line[1])
cost = int(line[2])
manager.add(deadline, cost)
elif command == 'process':
result = manager.process()
sys.stdout.write(f"{result[0]} {result[1]}\n")
if __name__ == '__main__':
main()
