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

📅  最后修改于: 2021-04-24 16:57:01             🧑  作者: 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.

方法1 :(强力)

时间复杂度: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

方法2 :(有效方法)

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

4.对于新索引i,我们需要添加当前索引x i与所有先前索引x k i的差

5.如果我们以非降序对所有点进行排序,则可以轻松地计算出在O(N)时间中每对坐标之间沿一个轴的所需距离之和,并使用上述方法从左到右处理点。
同样,我们不必担心两个点是否相等,在以非降序对点进行排序之后,我们说,当且仅当点x i-1在排序数组中更早出现时,点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.

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


Java脚本


输出 :

22

时间复杂度: O(nlogn)