Manhattan distance

3.5

6 votes
Algorithms, Basics of Greedy Algorithms, Greedy Algorithms
Problem

There are N towns in a coordinate plane. Town i is located at coordinate (xi,yi). The distance between town i and town j is |xixj|+|yiyj|. Your task is to compute the sum of the distance between each pair of towns.

Input format

  • The first line contains an integer T denoting the number of test cases.
  • The first line of each test case contains an integer N denoting the total number of towns.
  • Next N lines contain two space-separated integers xi and yi denoting a town at coordinate (xi,yi).

Output format

For each test case, print the sum of the distance between each pair of towns in a new line.

Constraints

1T10001N2000000xi,yi1000000000

It is guaranteed that the sum of N over T test cases does not exceed 1e6.

Sample Input
2
1
1 8
3
1 5
2 2
3 1
Sample Output
0
12
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

For the first testcase, there are no possible pairs of town. Therefore, the sum is 0.

For the second testcase, there are only 3 possible pairs (town1,town2), (town1,town3​​) and (town2,town3). Therefore, the sum of distance between every pair of towns is 12.

Editor Image

?