Drawing Arrows
InterviewTime limit1sMemory limit256 MB
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, points are given, and each point has one of colors. For convenience, colors are represented by numbers from 1 to , and all point coordinates are distinct.
For each point , we want to connect it to another point using a straight arrow that starts at . Here, must be the point of the same color as that is closest to . If two or more points are tied for closest, choose any one of them.
For each point , draw a single arrow going to the that satisfies the condition above. In particular, if no other point of the same color exists, then . Here denotes the length of arrow .
For example, representing points as ordered pairs (coordinate, color), let = (0, 1), = (1, 2), = (3, 1), = (4, 1). The arrow of point , , connects . The arrows of points and , and , connect and respectively. For point , no other point of the same color exists. Therefore the sum of all arrow lengths is .
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, .
Input
The standard input provides the following information. The first line contains an integer , the number of points. Each of the next lines contains two integers and , 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 and color of a point satisfy 0 ≤ ≤ 109 and 1 ≤ ≤ respectively.