Approach
Sorting and greedy selection
For ABC364 D — K-th Nearest, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 64 lines of Python from the credited upstream file abc364_d.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3from bisect import bisect_left, bisect_right4from typing import List5 6 7def bisect_lt(sorted_array: List[int], value: int):8 """Find the largest element < x and its index, or None if it doesn't exist."""9 10 if sorted_array[0] < value:11 index: int = bisect_left(sorted_array, value) - 112 13 return index, sorted_array[index]14 15 return None, None16 17 18def bisect_le(sorted_array: List[int], value: int):19 """Find the largest element <= x and its index, or None if it doesn't exist."""20 21 if sorted_array[0] <= value:22 index: int = bisect_right(sorted_array, value) - 123 24 return index, sorted_array[index]25 26 return None, None27 28 29def main():30 import sys31 32 input = sys.stdin.readline33 34 n, q = map(int, input().split())35 inf = 10**2036 a = [-inf] + sorted(list(map(int, input().split()))) + [inf]37 38 def f(wj, bj, kj):39 lower, upper = bj - wj, bj + wj40 41 i, _ = bisect_lt(a, lower) 42 j, _ = bisect_le(a, upper) 43 44 return j - i >= kj45 46 for _ in range(q):47 bj, kj = map(int, input().split())48 49 ng, ok = -1, 2 * 10**850 51 while abs(ok - ng) > 1:52 wj = (ok + ng) 253 54 if f(wj, bj, kj):55 ok = wj56 else:57 ng = wj58 59 print(ok)60 61 62if __name__ == "__main__":63 main()64