본문 바로가기
알고리즘/백준

백준 1002번 - 터렛 (Java 8)

by latissimus 2022. 2. 25.

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

 

1002번: 터렛

각 테스트 케이스마다 류재명이 있을 수 있는 위치의 수를 출력한다. 만약 류재명이 있을 수 있는 위치의 개수가 무한대일 경우에는 -1을 출력한다.

www.acmicpc.net

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

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;


        int numOfCase = Integer.parseInt(br.readLine());
        int arr[] = new int[numOfCase];
        for(int i=0; i<numOfCase; i++){
            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());

            //case 1: 터렛의 좌표(원의 중심)가 동일한 경우
            //마린까지 거리(반지름의 길이)도 같다면 동일한 원으로 무한대 -> -1 저장
            //마린까지 거리(반지름의 길이)가 다르면 만나지 않는다. -> 0 저장
            if(x1 == x2 && y1 == y2){
                if(r1 == r2){
                    arr[i] = -1;
                }else{
                    arr[i] = 0;
                }
                continue;
            }

            //case 2: 좌표가 하나라도 다른 경우

            //각 좌표의 차의 제곱을 활용해서 중심간의 거리의 제곱을 구한다.
            int side1 = x1 - x2;
            int side2 = y1 - y2;
            int centorToCentorDistancePow = (int) (Math.pow(side1, 2) + Math.pow(side2, 2)); //거리 제곱 = 변1의 제곱 + 변2의 제곱

             
            //반지름 합,차의 제곱 -> r1, r2은 양수로 주어진다.
            int sumOfRadiusPow = (int) Math.pow(r1 + r2,2);
            int difOfRadiusPow = (int) Math.pow(r1 - r2,2);
            
            //조건식 순서대로 4가지 경우와 나머지
            //원이 외접, 내접하는 경우
            if(centorToCentorDistancePow == sumOfRadiusPow || centorToCentorDistancePow == difOfRadiusPow){
                arr[i] = 1;
            //원이 한 원의 외부에 있어서 만나지 않거나, 내부에서 만나지 않는 경우
            } else if(centorToCentorDistancePow > sumOfRadiusPow || centorToCentorDistancePow < difOfRadiusPow){
                arr[i] = 0;
            //(나머지) 원이 두 점에서 만나는 경우
            } else{
                arr[i] = 2;
            }
        }

        for(int each : arr){
            System.out.println(each);
        }
    }
}

 

풀이 : 

 

각 터렛에서 터렛의 좌표가 중심이고, 마린까지의 거리가 반지름이라 가정했을때, 해당 값들을 이용하여 원을 그려보면, 존재할 수 있는 위치는 두 원이 겹치는 부분의 개수라고 할 수 있다.

 

즉, 각 터렛의 좌표는 원의 중심 좌표, 마린까지의 거리는 반지름이라고 가정하고 풀면 된다.

댓글