All problems

Problem 432

Minimum Cost to Connect Points

Medium · 20 pts · Graph, Minimum Spanning Tree, Union Find

Problem

You are given N points on a grid. Connecting two points (x1, y1) and (x2, y2) costs their Manhattan distance |x1 - x2| + |y1 - y2|. Connect all the points so that every point can reach every other one through the connections, at the minimum total cost. This is a minimum spanning tree over the complete graph of the points; Prim's algorithm in O(N²) works well for N up to 1000.

Input

First line: N. Next N lines: the coordinates x y of a point.

Output

Print the minimum total cost.

Constraints

1 <= N <= 1000; -1000000 <= x, y <= 1000000; points are distinct

Example input

5
0 0
2 2
3 10
5 2
7 0

Example output

20

Explanation

For the points (0,0), (2,2), (3,10), (5,2) and (7,0), the cheapest connections cost 4 + 3 + 4 + 9 = 20 in total.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Edge Reversals Next: Shortest Paths in a DAG