problems / 130

Closest Pair of Points

medium geometry sorting math 1500 ms · 256 MB

Closest Pair of Points

You are given n points on the plane with integer coordinates. Point i is (x_i, y_i). Several points may coincide.

Find the smallest squared Euclidean distance between two points with different indices, that is, the minimum of (x_i − x_j)^2 + (y_i − y_j)^2 over all pairs 1 ≤ i < j ≤ n.

Input

The first line contains an integer n (2 ≤ n ≤ 2·10^5), the number of points.

Each of the next n lines contains two integers x_i and y_i (−10^9 ≤ x_i, y_i ≤ 10^9), the coordinates of point i.

Output

Print one integer: the minimum squared distance between two points with different indices.

Notes

The answer can be as large as 8·10^18, so it fits in a signed 64-bit integer but not in a 32-bit one. Squaring a coordinate difference also needs 64-bit arithmetic.

In the first example the closest pair is (2, 3) and (3, 4), at squared distance 1 + 1 = 2.

In the second example two points coincide, so the answer is 0.

Example 1

Input

6
2 3
12 30
40 50
5 1
12 10
3 4

Output

2

Example 2

Input

4
-7 4
0 0
100 -100
-7 4

Output

0

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

Hint 1

Checking every pair is about 2 times 10^10 distance computations, too slow. Once you have a candidate best distance, which points can possibly beat it when compared with a given point, and how can sorting help you skip the others?

Hint 2

Split the points by x and solve each half recursively. Only points within the current best distance of the split line can form a closer cross pair, and if those points are kept sorted by y, each one needs to be compared with only a constant number of neighbours. Use 64-bit arithmetic for squared differences.

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

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