Problem 565
Find Right Interval
Medium · 20 pts · Array, Binary Search, Sorting
Problem
You are given N intervals [start, end], and all the start values are different. The right interval of interval i is the interval j whose start is the smallest start that is greater than or equal to end_i. Interval j may be i itself (when start_i >= end_i, which happens only if start equals end). For every interval print the index j of its right interval, or -1 if none exists. Sort the starts with their indices and binary search each end.
Input
The first line contains N. Each of the next N lines contains start and end of one interval (indices are 0-based, in input order).
Output
Print N integers separated by spaces: the right interval index for each interval, or -1.
Constraints
1 <= N <= 100000; -10^6 <= start <= end <= 10^6; all starts are distinct
Example input
3 3 4 2 3 1 2
Example output
-1 0 1
Explanation
For intervals [3,4], [2,3] and [1,2]: interval 0 ends at 4 and no start is at least 4, so -1. Interval 1 ends at 3 and interval 0 starts at 3, so 0. Interval 2 ends at 2 and interval 1 starts at 2, so 1. The answer is -1 0 1.