Manhattan distance
Practice
3.5 (6 votes)
Algorithms
Basics of greedy algorithms
Greedy algorithms
Problem
83% Success 1976 Attempts 10 Points 1s Time Limit 256MB Memory 1024 KB Max Code

There are $$N$$ towns in a coordinate plane. Town $$i$$ is located at coordinate \((x_i,y_i)\). The distance between town $$i$$ and town $$j$$ is \(|x_i-x_j|+|y_i-y_j|\). 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 \(x_i\) and \(y_i\) denoting a town at coordinate \((x_i,y_i)\).

Output format

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

Constraints

\(1 \le T \le 1000\\ 1 \le N \le 200000\\ 0 \le x_i,y_i \le 1000000000\)

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

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:10
9 votes
Tags:
AlgorithmsBasics of Greedy AlgorithmsC++Greedy Algorithms
Points:10
11 votes
Tags:
HashingGreedy AlgorithmsBasics of Greedy AlgorithmsAlgorithms
Points:10
6 votes
Tags:
AlgorithmsGreedy Algorithms