Sum of Manhattan distances between all pairs of points

Given n integer coordinates. The task is to find sum of manhattan distance between all pairs of coordinates.
Manhattan Distance between two points (x1, y1) and (x2, y2) is:
|x1 – x2| + |y1 – y2|

Examples :

Input : n = 4
        point1 = { -1, 5 }
        point2 = { 1, 6 }
        point3 = { 3, 5 }
        point4 = { 2, 3 }
Output : 22
Distance of { 1, 6 }, { 3, 5 }, { 2, 3 } from 
{ -1, 5 } are 3, 4, 5 respectively.
Therefore, sum = 3 + 4 + 5 = 12

Distance of { 3, 5 }, { 2, 3 } from { 1, 6 } 
are 3, 4 respectively.
Therefore, sum = 12 + 3 + 4 = 19

Distance of { 2, 3 } from { 3, 5 } is 3.
Therefore, sum = 19 + 3 = 22.

Method 1: (Brute Force)
The idea is to run two nested loop i.e for each each point, find manhattan distance for all other points.

for (i = 1; i < n; i++)
for (j = i + 1; j < n; j++)
sum += ((xi – xj) + (yi – yj))

Below is the implementation of this approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to find sum of Manhattan distance
// between all the pairs of given points
#include <bits/stdc++.h>
using namespace std;
  
// Return the sum of distance between all
// the pair of points.
int distancesum(int x[], int y[], int n)
{
    int sum = 0;
  
    // for each point, finding distance to
    // rest of the point
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            sum += (abs(x[i] - x[j]) +
                    abs(y[i] - y[j]));
    return sum;
}
  
// Driven Program
int main()
{
    int x[] = { -1, 1, 3, 2 };
    int y[] = { 5, 6, 5, 3 };
    int n = sizeof(x) / sizeof(x[0]);
    cout << distancesum(x, y, n) << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find sum of Manhattan distance
// between all the pairs of given points
  
import java.io.*;
  
class GFG {
      
    // Return the sum of distance between all
    // the pair of points.
    static int distancesum(int x[], int y[], int n)
    {
        int sum = 0;
  
        // for each point, finding distance to
        // rest of the point
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                sum += (Math.abs(x[i] - x[j]) + 
                            Math.abs(y[i] - y[j]));
        return sum;
    }
  
    // Driven Program
    public static void main(String[] args)
    {
        int x[] = { -1, 1, 3, 2 };
        int y[] = { 5, 6, 5, 3 };
        int n = x.length;
          
        System.out.println(distancesum(x, y, n));
    }
}
  
// This code is contributed by vt_m.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to find sum of 
# Manhattan distance between all 
# the pairs of given points
  
# Return the sum of distance 
# between all the pair of points.
def distancesum (x, y, n):
    sum = 0
      
    # for each point, finding distance
    # to rest of the point
    for i in range(n):
        for j in range(i+1,n):
            sum += (abs(x[i] - x[j]) +
                        abs(y[i] - y[j]))
      
    return sum
  
# Driven Code
x = [ -1, 1, 3, 2 ]
y = [ 5, 6, 5, 3 ]
n = len(x)
print(distancesum(x, y, n) )
  
# This code is contributed by "Sharad_Bhardwaj".

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to find sum of Manhattan distance
// between all the pairs of given points
using System;
  
class GFG {
      
    // Return the sum of distance between all
    // the pair of points.
    static int distancesum(int []x, int []y, int n)
    {
        int sum = 0;
  
        // for each point, finding distance to
        // rest of the point
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                sum += (Math.Abs(x[i] - x[j]) + 
                            Math.Abs(y[i] - y[j]));
        return sum;
    }
  
    // Driven Program
    public static void Main()
    {
        int []x = { -1, 1, 3, 2 };
        int []y = { 5, 6, 5, 3 };
        int n = x.Length;
          
        Console.WriteLine(distancesum(x, y, n));
    }
}
  
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program to find sum
// of Manhattan distance 
// between all the pairs 
// of given points
  
// Return the sum of distance
// between all the pair of points.
function distancesum( $x, $y, $n)
{
    $sum = 0;
  
    // for each point, finding 
    // distance to rest of 
    // the point
    for($i = 0; $i < $n; $i++)
        for ($j = $i + 1; $j < $n; $j++)
            $sum += (abs($x[$i] - $x[$j]) +
                     abs($y[$i] - $y[$j]));
    return $sum;
}
  
    // Driver Code
    $x = array(-1, 1, 3, 2);
    $y = array(5, 6, 5, 3);
    $n = count($x);
    echo distancesum($x, $y, $n);
      
// This code is contributed by anuj_67.
?>

chevron_right



Output:

22

Time Complexity: O(n2)

Method 2: (Efficient Approach)
The idea is to use Greedy Approach. First observe, the manhattan formula can be decomposed into two independent sums, one for the difference between x coordinates and the second between y coordinates. If we know how to compute one of them we can use the same method to compute the other. So now we will stick to compute the sum of x coordinates distance.
Let’s assume that we know all distances from a point xi to all values of x’s smaller than xi. Let’s consider other points, the first one not smaller than xi, and call it xj. How to compute the distances from xj to all smaller points ? We can use the corresponding distances from from xi. Notice that each distance from xj to some xk, where xk < xj equals the distance from xi to xk plus the distance between xj and xi. If there are A points smaller than xj and S is the sum of distances from xi to smaller points, then the sum of distances from xj to smaller points equals S + (xjxi) * A.
If we sort all points in non-decreasing order, we can easily compute the desired sum of distances along one axis between each pair of coordinates in O(N) time, processing points from left to right and using the above method.
Also, we don’t have to concern if two points are equal coordinates, after sorting points in non-decreasing order, we say that a point xi is smaller xj if and only if it appears earlier in the sorted array.

Below is the implementation of this approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to find sum of Manhattan
// distances between all the pairs of
// given points
#include <bits/stdc++.h>
using namespace std;
  
// Return the sum of distance of one axis.
int distancesum(int arr[], int n)
{
    // sorting the array.
    sort(arr, arr + n);
  
    // for each point, finding the distance.
    int res = 0, sum = 0;
    for (int i = 0; i < n; i++) {
        res += (arr[i] * i - sum);
        sum += arr[i];
    }
  
    return res;
}
  
int totaldistancesum(int x[], int y[], int n)
{
    return distancesum(x, n) + distancesum(y, n);
}
  
// Driven Program
int main()
{
    int x[] = { -1, 1, 3, 2 };
    int y[] = { 5, 6, 5, 3 };
    int n = sizeof(x) / sizeof(x[0]);
    cout << totaldistancesum(x, y, n) << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find sum of Manhattan
// distances between all the pairs of
// given points
  
import java.io.*;
import java.util.*;
  
class GFG {
      
    // Return the sum of distance of one axis.
    static int distancesum(int arr[], int n)
    {
          
        // sorting the array.
        Arrays.sort(arr);
  
        // for each point, finding the distance.
        int res = 0, sum = 0;
        for (int i = 0; i < n; i++) {
            res += (arr[i] * i - sum);
            sum += arr[i];
        }
  
        return res;
    }
  
    static int totaldistancesum(int x[], 
                            int y[], int n)
    {
        return distancesum(x, n) + 
                        distancesum(y, n);
    }
  
    // Driven Program
    public static void main(String[] args)
    {
  
        int x[] = { -1, 1, 3, 2 };
        int y[] = { 5, 6, 5, 3 };
        int n = x.length;
        System.out.println(totaldistancesum(x,
                                        y, n));
    }
}
  
// This code is contributed by vt_m.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to find sum of Manhattan
# distances between all the pairs of
# given points
  
# Return the sum of distance of one axis.
def distancesum (arr, n):
      
    # sorting the array.
    arr.sort()
      
    # for each point, finding 
    # the distance.
    res = 0
    sum = 0
    for i in range(n):
        res += (arr[i] * i - sum)
        sum += arr[i]
      
    return res
      
def totaldistancesum( x , y , n ):
    return distancesum(x, n) + distancesum(y, n)
      
# Driven Code
x = [ -1, 1, 3, 2 ]
y = [ 5, 6, 5, 3 ]
n = len(x)
print(totaldistancesum(x, y, n) )
  
# This code is contributed by "Sharad_Bhardwaj".

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to find sum of Manhattan
// distances between all the pairs of
// given points
  
using System;
  
class GFG {
      
    // Return the sum of distance of one axis.
    static int distancesum(int []arr, int n)
    {
          
        // sorting the array.
        Array.Sort(arr);
  
        // for each point, finding the distance.
        int res = 0, sum = 0;
        for (int i = 0; i < n; i++) {
            res += (arr[i] * i - sum);
            sum += arr[i];
        }
  
        return res;
    }
  
    static int totaldistancesum(int []x, 
                            int []y, int n)
    {
        return distancesum(x, n) + 
                        distancesum(y, n);
    }
  
    // Driven Program
    public static void Main()
    {
  
        int []x = { -1, 1, 3, 2 };
        int []y = { 5, 6, 5, 3 };
        int n = x.Length;
        Console.WriteLine(totaldistancesum(x,
                                        y, n));
    }
}
  
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program to find sum of 
// Manhattan distances between 
// all the pairs of given points
  
// Return the sum of
// distance of one axis.
function distancesum($arr, $n)
{
    // sorting the array.
    sort($arr);
  
    // for each point, 
    // finding the distance.
    $res = 0; $sum = 0;
    for ($i = 0; $i < $n; $i++) 
    {
        $res += ($arr[$i] * $i - $sum);
        $sum += $arr[$i];
    }
  
    return $res;
}
  
function totaldistancesum($x, $y, $n)
{
    return distancesum($x, $n) + 
           distancesum($y, $n);
}
  
// Driver Code
$x = array(-1, 1, 3, 2);
$y = array(5, 6, 5, 3);
$n = sizeof($x);
echo totaldistancesum($x, $y, $n), "\n";
  
// This code is contributed by m_kit
?>

chevron_right



Output :

22

Time Complexity : O(nlogn)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : vt_m, jit_t



Article Tags :
Practice Tags :


4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.