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$$.
Submissions
Please login to view your submissions
Similar Problems
Points:10
57 votes
Tags:
AlgorithmsBasics of Greedy AlgorithmsGreedy Algorithms
Points:10
8 votes
Tags:
Greedy AlgorithmsAlgorithmsBasics of Greedy AlgorithmsGreedy algorithm
Points:10
6 votes
Tags:
AlgorithmsBasics of Greedy AlgorithmsC++Greedy Algorithms
Editorial