설명
숫자 0부터9까지와 +,-로 이루어진 리모컨에서 숫자버튼 일부가 고장났을 때 원하는 채널로 이동하려면 버튼을 최소 몇번 눌러야하는지 구하는 문제입니다.
작동 순서
1. 고장난 버튼의 개수와 이동하려는 채널 번호를 입력받습니다.
2. 고장난 버튼들을 입력받습니다.
3. 사용 가능한 버튼 목록에 고장난 버튼들을 제외한 수들을 입력합니다. 이때 사용 가능한 버튼 목록 맨앞자리에는 0을 넣는데 이경우는 버튼을 누르지 않는 경우를 위해서 넣었습니다.
4. 0번부터 999999번까지 모두 눌러보면서 버튼을 눌러야하는 최소 회수를 구합니다.
5. 이때 자릿값의 번호가 0번인 경우 그자릿수까지 버튼을 누르지 않은 경우이므로 ch 값을 바꿔줍니다.
6. 연산이 끝나면 계산된 최소의 횟수를 출력합니다.
소스코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.stream.IntStream;
public class 백준_1107번_리모컨 {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int N=Integer.parseInt(br.readLine());
int M=Integer.parseInt(br.readLine());
int[] broken = new int[M];
int ch=0, click, total;
if (M>0) {
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) {
broken[i] = Integer.parseInt(st.nextToken());
}
}
int[] button=new int[11-M];
int min=Math.abs(N-100);
button[0]=1;
for(int i=0, j=1; i<10; i++){
int finalI = i;
if(!IntStream.of(broken).anyMatch(x -> x == finalI))
button[j++]=i;
}
for(int hu_th=0;hu_th<button.length;hu_th++){
for(int te_th=0;te_th< button.length;te_th++){
for(int th=0;th<button.length;th++){
for(int hu=0;hu<button.length;hu++){
for(int ten=0;ten<button.length;ten++){
for(int one=0;one<button.length;one++){
ch=button[hu_th]*100000+button[te_th]*10000+button[th]*1000+button[hu]*100+button[ten]*10+button[one];
if(hu_th==0) ch=button[te_th]*10000+button[th]*1000+button[hu]*100+button[ten]*10+button[one];
if(te_th==0) ch=button[th]*1000+button[hu]*100+button[ten]*10+button[one];
if(th==0) ch=button[hu]*100+button[ten]*10+button[one];
if(hu==0) ch=button[ten]*10+button[one];
if(ten==0) ch=button[one];
if(one==0) ch=100;
if(ch>99999) click=6;
else if(ch>9999) click=5;
else if(ch>999) click=4;
else if(ch>99) click=3;
else if(ch>9) click=2;
else click=1;
total=Math.abs(ch-N)+click;
if(min>total) min=total;
}
}
}
}
}
}
System.out.print(min);
}
}
후기
문제풀이를 할때 정말 무식하게 푼 것 같습니다. 답을 맞춘것에만 만족하지 않고 계속해서 알고리즘 설계 능력을 발전시켜야할것 같습니다.