Hacker Land

3.2

5 votes
Graphs, Algorithms, Minimum Spanning Tree
Problem

There are total N Hacker-cities in a plane. Each city is located on coordinates (X[i],Y[i]) and there can be any number of cities on the same coordinates.

You have to make these cities connected by constructing some roads in such a way that it is possible to travel between every pair of cities by traversing the roads. The cost of constructing one road between any two cities is the minimum of the absolute difference between their X and Y coordinates.

As you want to earn more and more, you decided to do this in the most optimal way possible, such that the total cost of constructing these roads is minimal. You have to return the minimum money you need to spend on connecting all the cities.

Input Format:

  • The first line contains an integer T, denoting the number of test cases.
  • The first line of each test case contains a single integer N denoting the number of cities.
  • The second line of each test case contains N space-separated integers denoting the X coordinates of the N cities.
  • The third line of each test case contains N space-separated integers denoting the Y coordinates of the N cities

Output Format:

For each test case, print the minimum money needed to spend in connecting all the cities.

Constraints:

1<=T<=10

2<=N<=105

0<=X[i],Y[i]<=109

The sum of N over all test cases does not exceed 105.

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

For test case 1:
Here, if we construct a road between city 1 and 2, it will cost min(abs(13),abs(59))=2.
If we construct another road between city 2 and 3, it will cost min(abs(37),abs(98))=1
The total minimum cost possible is 2 + 1 = 3.

For test case 2:
Here if we construct a road between city 1 and 2, it will cost min(abs(24),abs(14))=2.
The total minimum cost possible is 2.

Editor Image

?