I♥TLE

Java、オンラインジャッジなど

0003-Is it a Right Triangle?

問題(外部リンク)

Is it a Right Triangle? | Aizu Online Judge

実装の概要

与えられた3辺で直角三角形が作れるということは三平方の定理(最長辺の2乗=他の辺の2乗の和)が成り立つことと同値です。入力をソートしておけば最長辺が必ず一番後ろになるので話が簡単になります。正の値なら2乗しても大小関係は変わらないため、この実装例では入力の時点で辺の長さの2乗を求めています。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());

        for(int i = 0; i < n; i++){
            String[] tmpStr = br.readLine().split(" ");
            int[] linesq = new int[3];

            //読み込むついでに2乗にしておく
            for(int j = 0; j < 3; j++){
                linesq[j] = Integer.parseInt(tmpStr[j]);
                linesq[j] *= linesq[j];
            }

            Arrays.sort(linesq);

            //三平方の定理
            if(linesq[2] == linesq[1] + linesq[0] ){
                System.out.println("YES");
            }
            else {
                System.out.println("NO");
            }
        }
    }
}