[BOJ] 8938λ² | μ¬λ₯κΎΌ (Java)
2024. 8. 1. 00:22γCoding Test/BOJ
πλ¬Έμ 보λ¬κ°κΈ°
Solution
μ΄λΆ νμ(Binary Search) μκ³ λ¦¬μ¦μΌλ‘ ν μ μμ΅λλ€. μ¬λ μμΉλ₯Ό μ μ₯νλ λ°°μ΄μ μ€λ¦μ°¨μμΌλ‘ μ λ ¬ν λ€, λλ¬Όλ€μ μμΉλ₯Ό μννλ©΄μ `L` μ¬κ±°λ¦¬ λ΄μ λ€μ΄μ€λ μ¬λλ₯Ό μ°ΎμΌλ©΄ λ©λλ€. μ¦, λ‘μ§μ μμλλ λ€μκ³Ό κ°μ΅λλ€.
- μ¬λ μμΉ λ°°μ΄μ μ€λ¦μ°¨μμΌλ‘ μ λ ¬
- λλ¬Όλ€μ μ’νλ₯Ό μν
- νμ¬ λλ¬Όμ `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
λ°μν
'Coding Test > BOJ' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[BOJ] 2477λ² | μ°ΈμΈλ° (Java) (0) | 2024.07.30 |
---|---|
[BOJ] 20056λ² | λ§λ²μ¬ μμ΄μ νμ΄μ΄λ³Ό (Java) (1) | 2024.07.25 |
[BOJ] 12904λ² | Aμ B (C++) (0) | 2024.03.28 |
[BOJ] 14891λ² | ν±λλ°ν΄ (C++) (0) | 2024.03.24 |
[BOJ] 2636λ² | μΉμ¦ (C++) (1) | 2024.03.22 |