公式

B - Farthest Point 解説 by en_translator


In this problem, you are asked to find the distance between every pair of points, and find the maximum distance from each point as well as the index of the furthest point.

One can find the Euclidean distance between two points by following the expression in the problem statement. However, the ordering of the Euclidean distance and the distance squared are the same, so one can manage squared Euclidean distances to use only integers in the implementation.

In order to find the point with the minimum index that achieves the maximum distance, for instance, one can inspect the points in ascending order of indices, and update the index when the maximum value is updated.

For more details, please refer to the sample code.

Sample code (C++):

#include <bits/stdc++.h>
using namespace std;

int main() {
  int n;
  cin >> n;
  vector<int> x(n), y(n);
  for (int i = 0; i < n; ++i) {
    cin >> x[i] >> y[i];
  }

  for (int i = 0; i < n; ++i) {
    int max_dist = 0; // Maximum distance squared
    int idx = -1;     // Index of point that maximzes the distance (0-indexed)
    for (int j = 0; j < n; ++j) {
      int dist = (x[i] - x[j]) * (x[i] - x[j]) +
                 (y[i] - y[j]) * (y[i] - y[j]); // Squared distance of point i and j
      if (max_dist < dist) {
        // If the maximum distance is updated
        max_dist = dist;
        idx = j;
      }
    }
    cout << idx + 1 << endl;
  }
}

投稿日時:
最終更新: