Drawing Arrows
InterviewTime limit2sMemory limit512 MB
Each point shoots an arrow to the nearest same-colored point; find the total length of all N arrows. Points are given unsorted, so sort them by position first.
- Level
Medium4 of 10
- Topics
- Sorting, Hash map, Array, Implementation
- Solved
- No attempts yet
Problem
On a straight line, the nonnegative integers 0, 1, 2, ... that represent positions are placed at equal intervals toward the right. Among these positions, points are given at N of them, one point per position (<Figure 1>). All given points have distinct positions. The distance between two points is the difference of the numbers that represent their positions. In <Figure 1>, 4 points are given, and the distance between points a and b is 3.

Each point has one of N colors. For convenience, colors are denoted by the numbers 1 through N.
For each point p, we want to connect it to another point q with a straight arrow that starts at p. Here, point q must be the point closest to p among the points that have the same color as p. If two or more points are closest, choose any one of them.
For every point, another point with the same color always exists. Therefore, from each point p, an arrow that satisfies the above condition and goes to some q can always be drawn.
For example, writing the points as ordered pairs (position, color), let a = (0,1), b = (1, 2), c = (3, 1), d = (4, 2), and e = (5, 1).

Drawing arrows under the above condition, as in <Figure 3> below, the arrow of point a connects to c. The arrows of points b and d connect to d and b, respectively. Also, the arrows of points c and e connect to e and c, respectively. Thus the sum of the lengths of all arrows is 3 + 3 + 2 + 3 + 2 = 13.

Given the positions and colors of the points, write a program that prints the sum of the lengths of the arrows starting at all points.
Input
The following information is given on standard input. The first line contains the integer N, the number of points. Each of the next N lines contains two integers x and y, which represent the coordinate and the 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 position x and the color y of each point satisfy 0 ≤ x ≤ 105 and 1 ≤ y ≤ N, respectively.