[알고리즘] 백준 1107

dlwl98·2022년 5월 17일
0

알고리즘공부

목록 보기
2/34
post-thumbnail

백준 1107번

해결 과정 요약

고장난 버튼을 담을 배열을 만들고
이 배열을 사용하여 특정채널을 누를 수 있는지 확인하는 check함수를 만든다.
just : +버튼과 -버튼만으로 N까지 도달하는 횟수.
0부터 1000000까지 모든 수를 check하면서
누를 수 있는 경우 아래 코드를 수행한다.

int k = to_string(i).size();
ret = min(ret, abs(i - N) + k);

풀이

#include <bits/stdc++.h>
using namespace std;
typedef unsigned int uint;
typedef long long ll;

int N,M,num,just,ret;
int but[10] = {1,1,1,1,1,1,1,1,1,1};

int check(int n){
    if(n < 10){
        if(but[n]) return 1;
        else return 0;
    }
    else{
        if(but[n%10]) return check(n/10);
        else return 0;
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    cin >> N >> M;
    just = abs(100 - N);
    for(int i=0; i<M; i++){
        cin >> num;
        but[num] = 0;
    }
    ret = just;
    for(int i=0; i<1000001; i++){
        if(check(i)){
            int k = to_string(i).size();
            ret = min(ret, abs(i - N) + k);
        }
    }
    
    cout << ret;
    return 0;
}

0개의 댓글