[BOJ] 8938번 | 사λƒ₯κΎΌ (Java)

2024. 8. 1. 00:22ㆍCoding Test/BOJ

πŸ”—λ¬Έμ œ λ³΄λŸ¬κ°€κΈ°

 

 

Solution

이뢄 탐색(Binary Search) μ•Œκ³ λ¦¬μ¦˜μœΌλ‘œ ν’€ 수 μžˆμŠ΅λ‹ˆλ‹€. μ‚¬λŒ€ μœ„μΉ˜λ₯Ό μ €μž₯ν•˜λŠ” 배열을 μ˜€λ¦„μ°¨μˆœμœΌλ‘œ μ •λ ¬ν•œ λ’€, λ™λ¬Όλ“€μ˜ μœ„μΉ˜λ₯Ό μˆœνšŒν•˜λ©΄μ„œ `L` 사거리 내에 λ“€μ–΄μ˜€λŠ” μ‚¬λŒ€λ₯Ό 찾으면 λ©λ‹ˆλ‹€. 즉, 둜직의 μˆœμ„œλ„λŠ” λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€.

 

  1. μ‚¬λŒ€ μœ„μΉ˜ 배열을 μ˜€λ¦„μ°¨μˆœμœΌλ‘œ μ •λ ¬
  2. λ™λ¬Όλ“€μ˜ μ’Œν‘œλ₯Ό 순회
    • ν˜„μž¬ λ™λ¬Όμ˜ `x` μ’Œν‘œμ™€ κ°€μž₯ κ°€κΉŒμš΄ μ‚¬λŒ€μ˜ μ’Œν‘œλ₯Ό 탐색 (`y` μ’Œν‘œλŠ” 고정값이기에 μƒμˆ˜λ‘œ 항상 μžˆλŠ” 수)
    • νƒμƒ‰ν•œ μ‚¬λŒ€μ™€μ˜ 거리가 `L` μ΄ν•˜μ΄λ©΄ 탐색 μ’…λ£Œ
      • μž‘μ„ 수 μžˆλŠ” 동물 수 +1ν•˜κ³ , λ‹€μŒ 동물 μ’Œν‘œλ‘œ 순회
    • νƒμƒ‰ν•œ μ‚¬λŒ€μ™€μ˜ 거리가 `L`보닀 크닀면, ν˜„μž¬ λ™λ¬Όμ˜ x μ’Œν‘œμ—μ„œ μ‚¬λŒ€κ°€ μ™Όμͺ½μ— μžˆλŠ”μ§€ 였λ₯Έμͺ½μ— μžˆλŠ”μ§€ νŒŒμ•…
      • μ‚¬λŒ€κ°€ μ™Όμͺ½μ— μžˆλ‹€λ©΄ `left = mid + 1`
      • μ‚¬λŒ€κ°€ 였λ₯Έμͺ½μ— μžˆλ‹€λ©΄ `right = mid - 1`

 

Source Code

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

public class BOJ8983 {
    private static int M, N, L;
    private static long[] ShootingPositions;

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1 << 16);
        String[] inputs = br.readLine().split(" ");

        M = Integer.parseInt(inputs[0]);
        N = Integer.parseInt(inputs[1]);
        L = Integer.parseInt(inputs[2]);

        inputs = br.readLine().split(" ");
        ShootingPositions = new long[M];

        for (int i = 0; i < M; i++) {
            ShootingPositions[i] = Long.parseLong(inputs[i]);
        }

        Arrays.sort(ShootingPositions);
        int answer = 0;

        for (int i = 0; i < N; i++) {
            inputs = br.readLine().split(" ");
            long x = Long.parseLong(inputs[0]), y = Long.parseLong(inputs[1]);

            answer += binarySearch(0, M - 1, x, y);
        }

        System.out.println(answer);
        br.close();
    }

    public static int binarySearch(int left, int right, long animalX, long animalY) {
        boolean canHunt = false;

        while (left <= right) {
            int mid = (left + right) / 2;
            long turretX = ShootingPositions[mid];
            long distance = Math.abs(turretX - animalX) + animalY;

            // 사λƒ₯ κ°€λŠ₯ν•œ 거리이면 이뢄 탐색 쀑단
            if (distance <= L) {
                canHunt = true;
                break;
            }

            if (turretX < animalX) left = mid + 1;
            else                   right = mid - 1;
        }

        return canHunt ? 1 : 0;
    }
}

728x90
λ°˜μ‘ν˜•