본문 바로가기

완전 탐색 (Brute Force)

백준 1107 리모컨

문제 링크: https://www.acmicpc.net/problem/1107

불러오는 중입니다...

0번 채널부터 1000000번 채널까지 어느채널에서 가장 적은 수의 버튼을 눌러서 n번 채널로 갈수 있는지 체크하면 된다. 처음에는 isPossible 함수(주어진 채널을 누를때 고장난 버튼이 있는지 확인하는 함수, 주어진 채널이 0일때는 while(num)문이 아예 돌아가지 않기 때문에 예외 처리를 했다.)와 numDigits 함수(주어진 채널로 갈때 눌러야 하는 버튼수를 리턴하는 함수)를 이용해서 아래와 같이 코드를 짰다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <bits/stdc++.h>
using namespace std;
 
int n, m;
bool broken[11];
 
bool isPossible(int num) {
    if(num == 0) {
        if(broken[0== truereturn false;
        return true;
    }
    while(num) {
        if(broken[num % 10]) return false;
        num /= 10;
    }
    return true;
}
 
int numDigits(int num) {
    if(num == 0return 1;
    int ret = 0;
    while(num) {
        ret++;
        num /= 10;
    }
    return ret;
}
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    cin >> n >> m;
    while(m--) {
        int b;
        cin >> b;
        broken[b] = true;
    }
 
    int ans = abs(n - 100);
    for(int ch = 0; ch <= 1000000; ch++) {
        if(isPossible(ch))
            ans = min(ans, abs(ch - n) + numDigits(ch));
    }
 
    cout << ans << '\n';
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

두개 함수 모두, while(num)을 가지고 있기에 하나의 function으로 줄일수 있을거 같았다. 그래서 numDigits 함수가 고장난 버튼이 없을때는 눌러야 하는 버튼수를, 고장난 버튼이 있을때는 0을 리턴하게끔 바꿔서 아래와 같이 코드의 길이를 조금 줄일수 있었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <bits/stdc++.h>
using namespace std;
 
int n, m;
bool broken[11];
 
int numDigits(int num) {
    if(num == 0return broken[0] ? 0 : 1;
    int ret = 0;
    bool possible = true;
    while(num) {
        if(broken[num % 10]) possible = false;
        ret++;
        num /= 10;
    }
    return possible ? ret : 0;
 
}
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    cin >> n >> m;
    while(m--) {
        int b;
        cin >> b;
        broken[b] = true;
    }
 
    int ans = abs(n - 100);
    for(int ch = 0; ch <= 1000000; ch++) {
        if(numDigits(ch))
            ans = min(ans, abs(ch - n) + numDigits(ch));
    }
 
    cout << ans << '\n';
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

'완전 탐색 (Brute Force)' 카테고리의 다른 글

백준 6064 카잉 달력  (0) 2020.04.30
백준 14500 테트로미노  (0) 2020.04.29
백준 1476 날짜 계산  (0) 2020.04.29
백준 1018 체스판 다시 칠하기  (0) 2020.04.24
백준 2503 숫자 야구  (0) 2020.04.24