Skip to content
Related Articles

Related Articles

Find sum of Kth largest Euclidean distance after removing ith coordinate one at a time

Improve Article
Save Article
  • Last Updated : 28 Mar, 2022
Improve Article
Save Article

Given N integer coordinates where X[i] denotes the x-coordinate and Y[i] denotes the y-coordinate of the ith coordinate, the task is to find the sum of Kth largest euclidean distance between all the coordinate pairs except the ith coordinate for all possible values of i in the range [1, N].

Examples:

Input: X[] = {0, 0, 1, 1}, Y[] = {0, 1, 0, 1}, K = 2
Output: 4
Explanation:

  1. The coordinates except the 1st coordinate are {{0, 1}, {1, 0}, {1, 1}}. Their respective euclidean distances are {1.414, 1, 1}. Since K = 2, the second largest euclidean distance = 1.
  2. The coordinates except the 2nd coordinate are {{0, 0}, {1, 0}, {1, 1}}. Their respective euclidean distances are {1, 1, 1.414}. The second largest euclidean distance = 1.
  3. The coordinates except the 3rd coordinate are {{0, 1}, {0, 0}, {1, 1}}. Their respective euclidean distances are {1, 1.414, 1}. The second largest euclidean distance = 1.
  4. The coordinates except the 4th coordinate are {{0, 1}, {1, 0}, {0, 0}}. Their respective euclidean distances are {1.414, 1, 1}. The second largest euclidean distance = 1.

The sum of all second largest euclidean distances is 4.

Input: X[] = {0, 1, 1}, Y[] = {0, 0, 1}, K = 1
Output: 3.41421

Approach: The given problem can be solved by following the below steps:

  • Create a vector distances[] which store index p, q, and the euclidean distance between the pth and qth coordinate for all valid unordered pairs of (p, q) in the range [1, N].
  • Sort the vector distances in the order of decreasing distances.
  • For all values of i in the range [1, N], perform the following operation:
    • Create a variable cnt, which keeps track of the index of Kth largest element in distances vector. Initially, cnt = 0.
    • Iterate through the vector distances using a variable j, and increment the value of cnt by 1 if i != p and i != q where (p, q) are the indices of coordinates stored in distances[j].
    • If cnt = K, add the distance at current index j in distances vector into a variable ans.
    • The value stored in ans is the required answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the sum of the Kth
// maximum distance after excluding the
// ith coordinate for all i over the
// range [1, N]
double sumMaxDistances(int X[], int Y[],
                       int N, int K)
{
    // Stores (p, q) and the square of
    // distance between pth and qth
    // coordinate
    vector<pair<int, pair<int, int> > > distances;
 
    // Find the euclidean distances
    // between all pairs of coordinates
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
 
            // Stores the square of euclidean
            // distance between the ith and
            // the jth coordinate
            int d = (X[i] - X[j]) * (X[i] - X[j])
                    + (Y[i] - Y[j]) * (Y[i] - Y[j]);
 
            // Insert into distances
            distances.push_back({ d, { i, j } });
        }
    }
 
    // Stores the final answer
    double ans = 0;
 
    // Sort the distances vector in the
    // decreasing order of distance
    sort(distances.begin(), distances.end(),
         greater<pair<int, pair<int, int> > >());
 
    // Iterate over all i in range [1, N]
    for (int i = 0; i < N; i++) {
 
        // Stores the square of Kth maximum
        // distance
        int mx = -1;
 
        // Stores the index of Kth maximum
        // distance
        int cnt = 0;
 
        // Loop to iterate over distances
        for (int j = 0; j < distances.size(); j++) {
 
            // Check if any of (p, q) in
            // distances[j] is equal to i
            if (distances[j].second.first != i
                && distances[j].second.second != i) {
                cnt++;
            }
 
            // If the current index is the
            // Kth largest distance
            if (cnt == K) {
                mx = distances[j].first;
                break;
            }
        }
 
        // If Kth largest distance exists
        // then add it into ans
        if (mx != -1) {
 
            // Add square root of mx as mx
            // stores the square of distance
            ans += sqrt(mx);
        }
    }
 
    // Return the result
    return ans;
}
 
// Driver Code
int main()
{
    int X[] = { 0, 1, 1 };
    int Y[] = { 0, 0, 1 };
    int K = 1;
    int N = sizeof(X) / sizeof(X[0]);
 
    cout << sumMaxDistances(X, Y, N, K);
 
    return 0;
}

Java




// Java code for the above approach
import java.io.*;
import java.util.*;
import java.util.Collections;
 
// User defined Pair class
class Pair {
  int first;
  int second;
 
  // Constructor
  public Pair(int first, int second)
  {
    this.first = first;
    this.second = second;
  }
}
// User defined Pair with one element int and other as a
// pair
class Pair_next {
  int first;
  Pair second;
 
  // constructor
  public Pair_next(int first, Pair second)
  {
    this.first = first;
    this.second = second;
  }
}
 
// class to sort the elements in
// decreasing order of first element
class cmp implements Comparator<Pair_next> {
 
  public int compare(Pair_next p1, Pair_next p2)
  {
    return p2.first - p1.first;
  }
}
public class GFG {
 
  // Function to find the sum of the Kth
  // maximum distance after excluding the
  // ith coordinate for all i over the
  // range [1, N]
  static double sumMaxDistances(int X[], int Y[], int N,
                                int K)
  {
 
    // Stores (p, q) and the square of
    // distance between pth and qth
    // coordinate
    Vector<Pair_next> distances
      = new Vector<Pair_next>();
 
    // Find the euclidean distances
    // between all pairs of coordinates
    for (int i = 0; i < N; i++) {
      for (int j = i + 1; j < N; j++) {
 
        // Stores the square of euclidean
        // distance between the ith and
        // the jth coordinate
        int d = (X[i] - X[j]) * (X[i] - X[j])
          + (Y[i] - Y[j]) * (Y[i] - Y[j]);
 
        // Insert into distances
        Pair temp_pair = new Pair(i, j);
        Pair_next temp
          = new Pair_next(d, temp_pair);
 
        distances.add(temp);
      }
    }
 
    // Stores the final answer
    double ans = 0;
 
    // Sort the distances vector in the
    // decreasing order of distance
    Collections.sort(distances, new cmp());
 
    // Iterate over all i in range [1, N]
    for (int i = 0; i < N; i++) {
 
      // Stores the square of Kth maximum
      // distance
      int mx = -1;
 
      // Stores the index of Kth maximum
      // distance
      int cnt = 0;
 
      // Loop to iterate over distances
      for (int j = 0; j < distances.size(); j++) {
 
        // Check if any of (p, q) in
        // distances[j] is equal to i
        if (distances.get(j).second.first != i
            && distances.get(j).second.second
            != i) {
          cnt++;
        }
 
        // If the current index is the
        // Kth largest distance
        if (cnt == K) {
          mx = distances.get(j).first;
          break;
        }
      }
 
      // If Kth largest distance exists
      // then add it into ans
      if (mx != -1) {
 
        // Add square root of mx as mx
        // stores the square of distance
        ans += Math.sqrt(mx);
      }
    }
 
    // Return the result
    return ans;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int X[] = { 0, 1, 1 };
    int Y[] = { 0, 0, 1 };
    int K = 1;
    int N = X.length;
 
    System.out.println(sumMaxDistances(X, Y, N, K));
  }
}
 
// This code is contributed by rj13to.

Python3




# Python 3 program for the above approach
from math import sqrt
 
# Function to find the sum of the Kth
# maximum distance after excluding the
# ith coordinate for all i over the
# range [1, N]
def sumMaxDistances(X, Y, N, K):
   
    # Stores (p, q) and the square of
    # distance between pth and qth
    # coordinate
    distances = []
 
    # Find the euclidean distances
    # between all pairs of coordinates
    for i in range(N):
        for j in range(i + 1, N, 1):
 
            # Stores the square of euclidean
            # distance between the ith and
            # the jth coordinate
            d = int(X[i] - X[j]) * int(X[i] - X[j]) + int(Y[i] - Y[j]) * int(Y[i] - Y[j])
 
            # Insert into distances
            distances.append([d,[i, j]])
 
    # Stores the final answer
    ans = 0
 
    # Sort the distances vector in the
    # decreasing order of distance
    distances.sort(reverse = True)
 
    # Iterate over all i in range [1, N]
    for i in range(N):
       
        # Stores the square of Kth maximum
        # distance
        mx = -1
         
        # Stores the index of Kth maximum
        # distance
        cnt = 0
         
        # Loop to iterate over distances
        for j in range(0,len(distances), 1):
           
            # Check if any of (p, q) in
            # distances[j] is equal to i
            if (distances[j][1][0] != i and distances[j][1][0] != i):
                cnt += 1
 
            # If the current index is the
            # Kth largest distance
            if (cnt == K):
                mx = distances[j][0]
                break
 
        # If Kth largest distance exists
        # then add it into ans
        if (mx != -1):
 
            # Add square root of mx as mx
            # stores the square of distance
            ans += (sqrt(mx))
 
    # Return the result
    return ans
 
# Driver Code
if __name__ == '__main__':
    X = [0, 1, 1]
    Y = [0, 0, 1]
    K = 1
    N = len(X)
    print(sumMaxDistances(X, Y, N, K))
     
    # This code is contributed by ipg2016107.

 
 

Output: 

3.41421

 

Time Complexity: O(N2*log N + K*N2)
Auxiliary Space: O(N2)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!