개발 일기

백준 1002번 문제풀이 - 터렛 본문

백준 문제풀이

백준 1002번 문제풀이 - 터렛

종현종현 2021. 11. 24. 11:58

백준 1002번 문제

 

 

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

 

1002번: 터렛

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

www.acmicpc.net

 

문제를 해석하면 결국 두 원이 동일한 경우 -1, 두 원이 접하지 않을 때 0, 두 원이 한 점에서 접할 경우 1, 두 점에서 만나면 2를 출력하도록 하면 되는 문제이다.

 

 

 

 

 

코딩

 

public class Turret {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int T = Integer.parseInt(br.readLine());

        for (int i = 0; i < T; i++) {
            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());
            // 원 중심 거리의 제곱
            int d_square = (int)(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
            // 원 중심, 반지름이 같을 때
            if (x1 == x2 && y1 == y2 && r1 == r2) {
                sb.append(-1).append('\n');
            }
            // 두 원이 접하지 않을 경우
            else if (d_square > Math.pow(r1 + r2, 2) || d_square < Math.pow(r2 - r1, 2)) {
                sb.append(0).append('\n');
            }
            // 두 원이 한 점에서 접할 경우 (내접, 외접)
            else if (d_square == Math.pow(r1 + r2, 2) || d_square == Math.pow(r1 - r2, 2)) {
                sb.append(1).append('\n');
            }
            // 두 원이 두 점에서 만날 때
            else {
                sb.append(2).append('\n');
            }
        }
        System.out.println(sb);
    }
}

 

 

 

 

 

 

 

결과

 

 

 

 

 

 

느낀 점

 

두 원의 상태에 따라 출력하도록 하면 된다는 것을 안다면 쉬운 문제였다. 하지만 코딩을 하는 과정에서 문제가 생겼다.  Math클래스의 sqrt를 사용하여 원 중심간 거리를 제곱근으로 구하고 사용했지만 오차가 발생하여 틀리게 된 것이다.

Math클래스를 사용할 때 실제 수학과는 차이가 있다는 것을 항상 염두하고 사용해야겠다. 

Comments