Description:
https://interunia.unswcpmsoc.com/task/Horse%20Racing/
Thinking:
Preprocessing Horse Information:
Combine horse information into a list of tuples, horses
, where each tuple contains the horse index, starting position, and velocity.
Sort the horses by starting position in descending order. If two horses have the same starting position, sort them by velocity in descending order. This is because the horse with the highest starting position leads initially.
Constructing the Leading Horse Timeline:
- Use a stack
stack
to maintain the horses that could become the leader. - For each horse, check if it has the potential to overtake the current leading horse.
- If the current horse’s speed is less than or equal to the horse at the top of the stack, it can never overtake and is discarded.
- If the current horse’s speed is greater than the top horse’s, calculate when it will overtake the current leader.
- If the calculated overtaking time is invalid (e.g., earlier than the previous overtaking time), adjust the stack by removing horses that can no longer lead.
Handling Queries:
Use binary search to handle each query time t
in the times
list to find the corresponding leading horse.bisect.bisect_right(times, t) - 1
finds the first time point greater than t
, then subtract one to get the corresponding horse index.
Timeline Construction: We build a timeline that records the time points when the leading horse changes and the horse that leads during that period.
Binary Search for Queries: Since the timeline is sorted chronologically, we can efficiently find the leading horse for each query time using binary search.
Codes:
1 | n, q = map(int, input().split()) |