📌  相关文章
📜  所有点对之间的曼哈顿距离之和

📅  最后修改于: 2021-10-23 08:35:00             🧑  作者: Mango

给定n 个整数坐标。任务是找到所有坐标对之间的曼哈顿距离之和。
两点 (x 1 , y 1 ) 和 (x 2 , y 2 ) 之间的曼哈顿距离为:
|x 1 – x 2 | + |y 1 – y 2 |
例子 :

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.

方法一:(蛮力)

时间复杂度:O(n2)
这个想法是运行两个嵌套循环,即对于每个点,找到所有其他点的曼哈顿距离。

for (i = 1; i < n; i++)

  for (j = i + 1; j < n; j++)

    sum += ((xi - xj) + (yi - yj))

下面是这个方法的实现:

C++
// CPP Program to find sum of Manhattan distance
// between all the pairs of given points
#include 
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;
}


Java
// 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.


Python3
# 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".


C#
// 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.


PHP


Javascript


C++
// CPP Program to find sum of Manhattan
// distances between all the pairs of
// given points
#include 
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;
}


Java
// 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.


Python3
# 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".


C#
// 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.


PHP


Javascript


输出:

22

方法二:(高效方法)

  1. 这个想法是使用贪婪的方法。首先观察,曼哈顿公式可以分解为两个独立的和,一个是x坐标之间的差异,另一个是y坐标之间的差异。如果我们知道如何计算其中一个,我们可以使用相同的方法来计算另一个。所以现在我们将坚持计算x坐标距离的总和。
  2. 让我们假设我们已经计算了任何两点之间的距离总和,直到点x i-1对于所有x小于x i-1 的值,让这个总和为res ,现在我们必须计算任何两点之间的距离包含x i 的两个点,其中x i是下一个更大的点,要计算每个点与下一个更大的点x i的距离,我们可以将现有的差和resx i与所有点的距离相加x k小于x i 。因此,任何两点之间的总和现在将等于res + ( x i x k ) ,其中x i是测量差异的当前点, x k是所有小于x i的点。
  3. 因为对于每次计算x i保持不变,我们可以将求和简化为:

4. 对于新的索引 i ,我们需要加上当前索引x i与之前所有索引x k < x i的差值

5. 如果我们以非递减的顺序对所有点进行排序,我们可以很容易地计算出 O(N) 时间内每对坐标之间沿一个轴的所需距离总和,从左到右处理点并使用上述方法。
此外,我们不必关心两个点是否相等坐标,在按非递减顺序对点排序后,我们说点x i-1更小x i当且仅当它出现在已排序数组中的较早位置。
下面是这个方法的实现:

C++

// CPP Program to find sum of Manhattan
// distances between all the pairs of
// given points
#include 
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;
}

Java

// 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.

蟒蛇3

# 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".

C#

// 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.

PHP


Javascript


输出 :

22

时间复杂度: O(nlogn)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程