Parcel-delivery app~25 min2s · 256 MBtarget O((n + q * k) log n) time, O(n) spacetop-k
You work on a parcel-delivery app. A map shows depots, and the central hub sits at the position (0, 0). Depots open and close during the day. Dispatchers ask for the depots nearest to the hub that are open at that moment.
Your team lead asks: "At each ask, which k open depots are nearest to the hub?" The log holds up to 100,000 actions, and the dispatchers make at most 2,000 asks.
Write nearest_open(k, ops).
ops[i] = [kind, id, x, y] is one action. There are three kinds:
1: depot id opens at the position (x, y). Every id opens at most once.2: depot id closes. x and y are 0 and are ignored. If that depot is not open, because it never opened or has closed already, nothing happens. A closed depot never opens again.3: an ask. id, x and y are 0 and are ignored.x² + y². The nearest depot has the smallest distance, and the smaller id goes first on equal distances.k nearest open depots, nearest first. When fewer than k depots are open, the row lists all of them.Input: k = 3, ops = [[1, 4, 3, 4], [1, 9, -1, 2], [1, 2, 0, 5], [1, 7, 2, 2], [3, 0, 0, 0], [2, 9, 0, 0], [3, 0, 0, 0], [1, 5, -3, 4], [3, 0, 0, 0], [2, 8, 0, 0], [3, 0, 0, 0]]
Output: [[9, 7, 2], [7, 2, 4], [7, 2, 4], [7, 2, 4]]The distances are: depot 4: 25, depot 9: 5, depot 2: 25, depot 7: 8, depot 5: 25.
| Action | Open depots afterwards | Row |
|---|---|---|
| ask | 4, 9, 2, 7 | 9 (5), 7 (8), 2 (25): depots 2 and 4 tie, and 2 is smaller |
| close 9 | 4, 2, 7 | |
| ask | 4, 2, 7 | 7, 2, 4 |
| open 5 | 4, 2, 7, 5 | |
| ask | 4, 2, 7, 5 | 7, 2, 4: depot 5 also has 25, but the id 5 is larger |
| close 8 | 4, 2, 7, 5 (depot 8 was never open) | |
| ask | 4, 2, 7, 5 | 7, 2, 4 |
Input: k = 2, ops = [[3, 0, 0, 0], [1, 6, 1, 1], [3, 0, 0, 0]]
Output: [[], [6]]An ask with no open depot gives an empty row. An ask with fewer than k open depots lists them all.
Input: k = 1, ops = [[1, 3, 0, -2], [1, 1, 2, 0], [3, 0, 0, 0]]
Output: [[1]]Both depots are at distance 4, and depot 1 has the smaller id.
1 ≤ k ≤ 501 ≤ ops.length ≤ 100,000, and every row has 4 numbers. At most 2,000 rows are asks.0 ≤ id ≤ 1,000,000, and -30,000 ≤ x, y ≤ 30,000Sorting 50,000 open depots at an ask costs about 50,000 × 16 = 800,000 steps. For 2,000 asks that is 1,600,000,000 steps.
A heap of all depots gives the nearest in about 17 steps. An ask takes k of them off the heap and puts them back, which is about 2 × 50 × 17 = 1,700 steps. For 2,000 asks that is 3,400,000 steps.