https://www.acmicpc.net/problem/1107
1107번: 리모컨
첫째 줄에 수빈이가 이동하려고 하는 채널 N (0 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 고장난 버튼의 개수 M (0 ≤ M ≤ 10)이 주어진다. 고장난 버튼이 있는 경우에는 셋째 줄에는 고장난 버튼이
www.acmicpc.net
저는 구현을 통해 문제를 해결하였습니다.
0부터 1_000_000까지 해당 숫자가 n 까지 도달하는데 얼마나 걸리는지를 확인하였습니다.
이때 해당 숫자에 고장난 버튼이 있다면, 그 숫자는 카운트하지 않았고, 처음 초기화는 시작이 100 이기 때문에 |100-n|으로 초기화하여 문제를 풀었습니다.
package BOJ.etc;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class BOJ_1107 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int m = Integer.parseInt(br.readLine());
Set<Integer> isBroken = new HashSet<>();
if(m != 0){
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < m; i++) {
int num = Integer.parseInt(st.nextToken());
isBroken.add(num);
}
}
int result = cal(n, isBroken);
System.out.println(result);
}
private static final int PUSH_BROKEN = -1;
private static int cal(int n, Set<Integer> isBroken) {
int result = Math.abs(n - 100);
for(int i = 0 ; i <= 1_000_000 ; i++){
int length = check(i,isBroken);
if(length == PUSH_BROKEN){
continue;
}
result = Math.min(result,length + Math.abs(i-n));
}
return result;
}
private static int check(int num, Set<Integer> isBroken) {
if(num == 0 && isBroken.contains(0)){
return PUSH_BROKEN;
}
if(num == 0){
return 1;
}
int cnt = 0;
while(num > 0){
if(isBroken.contains(num%10)){
return PUSH_BROKEN;
}
num /= 10;
cnt++;
}
return cnt;
}
}
'알고리즘' 카테고리의 다른 글
백준 2805번 나무 자르기 (JAVA) (1) | 2023.11.11 |
---|---|
백준 2003번 수들의 합2 (JAVA) (0) | 2023.11.10 |
백준 14891번 톱니바퀴 (JAVA) (0) | 2023.11.08 |
백준 15683번 감시 (JAVA) (0) | 2023.11.07 |
백준 16234번 인구 이동 (JAVA) (3) | 2023.11.06 |