백준 1002 터렛[Java]

seren-dev·2022년 9월 1일
0

https://www.acmicpc.net/problem/1002

풀이

두 원의 중심의 거리(d)와 반지름 사이의 관계를 고려해 두 원의 접점을 찾는 문제다.

코드

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        StringBuilder sb = new StringBuilder();

        while (t-- > 0) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int x1 = Integer.parseInt(st.nextToken());
            int y1 = Integer.parseInt(st.nextToken());
            int r1 = Integer.parseInt(st.nextToken());
            int x2 = Integer.parseInt(st.nextToken());
            int y2 = Integer.parseInt(st.nextToken());
            int r2 = Integer.parseInt(st.nextToken());

            double d = Math.sqrt(Math.pow(x2- x1, 2) + Math.pow(y2-y1, 2));

            if (d == 0 && r1==r2)
                sb.append("-1\n");
            else if (d > r1 + r2 || d < Math.abs(r1- r2))
                sb.append("0\n");
            else if (d == r1+r2 || d == Math.abs(r1-r2))
                sb.append("1\n");
            else
                sb.append("2\n");
        }

        System.out.println(sb);

    }
}
  • d == 0 && r1==r2 : 두 원이 같으면 접점의 개수는 무한대이므로 -1
  • d > r1 + r2 || d < Math.abs(r1- r2) : 두 원의 접점이 없다.
  • d == r1+r2 || d == Math.abs(r1-r2) : 두 원의 접점이 1개
  • 그 이외의 경우는 두 원의 접점이 2개다.

0개의 댓글