최대 1 분 소요

[백준 1107] 리모컨

문제 링크

#include "header.h"
using namespace std;
int N, M;
int broken[10];

int check(int num){
    int cnt = 0;
    //맨 처음, 0이 고장 났다면 0, 고장나지 않았다면 1
    if(num == 0) {
        if(broken[0]){
            return 0;
        }else{
            return 1;
        }
    }

    while(num){
        int n = num % 10;
        if(broken[n]) return 0; // 누를 수 없다면 return 0;
        num /= 10;
        cnt++;
    }
    return cnt;
}
int main(){
    
    cin >> N;
    cin >> M;
    int start = 100;

    if(start == N){
        cout << 0 << endl;
        return 0;
    }

    for(int i=0; i<M; i++){
        int n;
        cin >> n;
        broken[n] = 1;
    }

    //-- 입력 끝

    int ans = abs(N - start); // 100에서 +1, -1씩 한 것 (최악의 경우)

    // 0 ~ 1000000 까지 돌면서 제일 적게 버튼을 누른 횟수를 찾는다.
    for(int i=0; i<=1000000; i++){
        int cmp = check(i); // 자릿수 찾기 (고장난 번호가 있으면 0)
        if(cmp){
            int press = abs(N - i) + cmp; // + 혹은 -를 누른 수 + 해당 숫자의 자릿수
            ans = min(ans, press); // 업데이트
        }
    }

    cout << ans << endl;

    return 0;
}

카테고리:

업데이트: