taiPyのお悩み解決ブログ

日々の発見をまとめます!

Javaの解答例:B - Farthest Point, トヨタ自動車プログラミングコンテスト2024#4(AtCoder Beginner Contest 348)

はじめに

自分用の備忘録。

メモ、ポイント

  • 問題文を読むこと。違う距離の出し方をしていて、それが要因で答えが違ったんですよね。
  • マイクロブレイク。詰まった時ほど休んでいこう。
  • 普通に、寝坊。30か40分遅れての参加で焦りが。。もう少し前に仮眠をとるか。

目次

問題と公式の解説

問題 atcoder.jp

解説 atcoder.jp

自作の解答例

コメントアウトしている、printはあれです。デバック用です。

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // input
        int N = sc.nextInt();
        int[] X = new int[N];
        int[] Y = new int[N];
        for (int i = 0; i < N; i++) {
            X[i] = sc.nextInt();
            Y[i] = sc.nextInt();
        }
        // process

        for (int i = 0; i < N; i++) {
            // distance
            int ans = 0;
            int tempX = X[i];
            int tempY = Y[i];
            double tempDistance = 0;
            // max?
            for (int j = 0; j < N; j++) {
                // d = Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
                double distance =  Math.sqrt((tempX - X[j]) * (tempX - X[j]) + (tempY - Y[j]) * (tempY - Y[j]));
                // int distance = Math.abs(tempX - X[j]) + Math.abs(tempY - Y[j]);
                // System.out.println("tempDistance" + tempDistance);
                // System.out.println("distance" + distance);
                // System.out.println(j);
                if (distance > tempDistance) {
                    tempDistance = distance;
                    ans = j + 1;
                }
            }
            // output
            System.out.println(ans);

        }
        
        sc.close();
    }
}

公式をJavaに変換

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] x = new int[n];
        int[] y = new int[n];
        for (int i = 0; i < n; ++i) {
            x[i] = scanner.nextInt();
            y[i] = scanner.nextInt();
        }

        for (int i = 0; i < n; ++i) {
            int max_dist = 0; //距離の2乗の最大値
            int idx = -1;     //距離が最大になる点の番号(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]); // 点i,jの距離の2乗
                if (max_dist < dist) {
                    // 距離の最大値が更新された場合
                    max_dist = dist;
                    idx = j;
                }
            }
            System.out.println(idx + 1);
        }
    }
}

参考文献

todo 必要あれば、追加。