problems / 238

Snapping Seeks to Keyframes

easy binary-search arrays 1000 ms · 256 MB

Snapping Seeks to Keyframes

You are working on a video player. A compressed video can only start decoding at a keyframe, so when the user drags the progress bar to some time, the player jumps to the keyframe closest to that time instead.

You are given the timestamps of the video's n keyframes in milliseconds, in increasing order, and q seek requests. For each request at time t, find the keyframe k that minimizes |t − k|. If two keyframes are equally close (one before t and one after it), choose the earlier one.

A request may lie before the first keyframe or after the last one.

Input

The first line contains two integers n and q (1 ≤ n, q ≤ 2·10^5): the number of keyframes and the number of seek requests.

The second line contains n integers k_1, k_2, …, k_n (0 ≤ k_1 < k_2 < … < k_n ≤ 10^9): the keyframe timestamps in milliseconds, strictly increasing.

Each of the next q lines contains one integer t (0 ≤ t ≤ 10^9): the time of a seek request in milliseconds.

Output

For each request, in input order, print one line with two integers: the timestamp of the chosen keyframe and its distance |t − k| from the request.

Notes

In the first example, the request at 3500 is exactly halfway between the keyframes at 2000 and 5000, so the earlier one, 2000, is chosen. The request at 7000 is a keyframe itself, and 9999 lies after the last keyframe.

In the second example there is only one keyframe, so every request snaps to it.

With n and q up to 2·10^5, scanning all keyframes for every request is too slow.

Example 1

Input

4 6
0 2000 5000 7000
3500
7000
9999
1000
4100
6000

Output

2000 1500
7000 0
7000 2999
0 1000
5000 900
5000 1000

Example 2

Input

1 3
500
0
500
1000000000

Output

500 500
500 0
500 999999500

Hints · reveal one at a time if you're stuck

Hint 1

The closest keyframe to t is either the last keyframe at or before t or the first one after it. No other keyframe can be closer.

Hint 2

The keyframes are sorted, so binary search finds the first keyframe that is at least t in O(log n). Compare it with the keyframe just before it, and remember that either one may not exist.

report an issue Prefer your own editor? sooks prep 238 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.