Under construction

Still being built. Things may change

Drawing Arrows

Interview

Time limit1sMemory limit256 MB

Summary
Each point shoots an arrow to the nearest same-colored point; compute the total length of all arrows.
Level

Medium4 of 10

Topics
Sorting, Hash map, Array, Implementation
Solved
No attempts yet

Problem

On a line, NN points are given, and each point has one of NN colors. For convenience, colors are represented by numbers from 1 to NN, and all point coordinates are distinct.

For each point pp, we want to connect it to another point qq using a straight arrow that starts at pp. Here, qq must be the point of the same color as pp that is closest to pp. If two or more points are tied for closest, choose any one of them.

For each point pp, draw a single arrow ℓp⃗\vec{\ell_{p}} going to the qq that satisfies the condition above. In particular, if no other point of the same color exists, then ∣ℓp⃗∣=0\left|\vec{\ell_{p}}\right|=0. Here ∣ℓp⃗∣\left|\vec{\ell_{p}}\right| denotes the length of arrow ℓp⃗\vec{\ell_{p}}.

For example, representing points as ordered pairs (coordinate, color), let p1p_1 = (0, 1), p2p_2 = (1, 2), p3p_3 = (3, 1), p4p_4 = (4, 1). The arrow of point p1p_1, ∣ℓp1⃗∣\left|\vec{\ell_{p_1}}\right|, connects p1→p3p_1\rightarrow p_3. The arrows of points p3p_3 and p4p_4, ∣ℓp3⃗∣\left|\vec{\ell_{p_3}}\right| and ∣ℓp4⃗∣\left|\vec{\ell_{p_4}}\right|, connect p3→p4p_3\rightarrow p_4 and p4→p3p_4\rightarrow p_3 respectively. For point p2p_2, no other point of the same color exists. Therefore the sum of all arrow lengths is ∣ℓp1⃗∣+∣ℓp2⃗∣+∣ℓp3⃗∣+∣ℓp4⃗∣=3+0+1+1=5\left|\vec{\ell_{p_1}}\right|+\left|\vec{\ell_{p_2}}\right|+\left|\vec{\ell_{p_3}}\right|+\left|\vec{\ell_{p_4}}\right|=3+0+1+1=5.

Given the coordinates and colors of the points, write a program that prints the sum of the lengths of the arrows starting at all points, that is, ∑p∣ℓp⃗∣\displaystyle\sum_{p}\left|\vec{\ell_{p}}\right|.

Input

The standard input provides the following information. The first line contains an integer NN, the number of points. Each of the next NN lines contains two integers xx and yy, representing the coordinate and color of a point.

Output

Print the sum of the lengths of the arrows starting at all points to standard output.

Constraints

In every subtask, the coordinate xx and color yy of a point satisfy 0 ≤ xx ≤ 109 and 1 ≤ yy ≤ NN respectively.

Examples3

  1. Example 1

    Input
    4
    0 1
    1 2
    3 1
    4 1
    
    Expected output
    5
    
  2. Example 2

    Input
    4
    1 1
    0 2
    4 3
    3 4
    
    Expected output
    0
    
  3. Example 3

    Input
    9
    10 2
    11 3
    20 2
    22 1
    25 1
    0 1
    4 2
    5 2
    7 2
    
    Expected output
    45