import numpy as np
from scipy.sparse import csr_matrix, lil_matrix
from collections import defaultdict
from scipy.sparse.csgraph import minimum_spanning_tree

def build_road_2():
	n = int(raw_input())
	cords = []
	for i in range(n):
		cords.append([int(e) for e in raw_input().split(" ")])
	cords = np.array(cords)
	x_cord = cords[:, 0]
	y_cord = cords[:, 1]
	# print x_cord
	sorted_indecies_x = np.argsort(x_cord)
	# print sorted_indecies_x
	sorted_indecies_y = np.argsort(y_cord)
	mutual_distance = lil_matrix((n, n), dtype=int)
	dict_edge_weight = defaultdict(list)
	for i in range(n-1):
		s1 = sorted_indecies_x[i]
		d1 = sorted_indecies_x[i+1]
		dis1 = abs(x_cord[s1]-x_cord[d1])
		dict_edge_weight[(s1, d1)].append(dis1)
		s2 = sorted_indecies_y[i]
		d2 = sorted_indecies_y[i + 1]
		dis2 = abs(y_cord[s2] - y_cord[d2])
		dict_edge_weight[(s2, d2)].append(dis2)
	for key, value in dict_edge_weight.iteritems():
		mutual_distance[key[0], key[1]] = min(value)
	ans = minimum_spanning_tree(mutual_distance)
	ans = ans.toarray().astype(int)
	print ans.sum()


if __name__ == "__main__":
	build_road_2()