Blog Content

    티스토리 뷰

    1463번 백준(Baekjoon)

    <문제>


    정수 X에 사용할 수 있는 연산은 다음과 같이 세 가지 이다.

    1. X가 3으로 나누어 떨어지면, 3으로 나눈다.

    2. X가 2로 나누어 떨어지면, 2로 나눈다.

    3. 1을 뺀다.

    정수 N이 주어졌을 때, 위와 같은 연산 세 개를 적절히 사용해서 1을 만들려고 한다. 연산을 사용하는 횟수의 최솟값을 출력하시오.


    <정답 코드>


    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
    51
    52
    53
    #include <iostream>
    #include <cstdio>
    #include <queue>
     
    using namespace std;
     
    int n;
    queue<int> q;
    bool check[1000001];
    int cnt = 0;
     
    void bfs()
    {
        q.push(n);
        check[n] = 1;
     
        while (!q.empty())
        {
            int size = q.size();
            for (int i = 0; i < size; i++)
            {
                int front = q.front();
                q.pop();
                if (front == 1)
                    return;
                if (front % 3 == 0 && check[front / 3== 0)
                {
                    q.push(front / 3);
                    check[front / 3= 1;
                }
                if (front % 2 == 0 && check[front / 2== 0)
                {
                    q.push(front / 2);
                    check[front / 2= 1;
                }
                if (check[front - 1== 0)
                {
                    q.push(front - 1);
                    check[front - 1= 1;
                }
            }
            cnt++;
        }
        return;
    }
     
    int main()
    {
        scanf("%d"&n);
        bfs();
        printf("%d\n", cnt);
        return 0;
    }
    cs


    'C++ 문제풀이' 카테고리의 다른 글

    1520번 백준(Baekjoon)  (0) 2018.10.01
    9095번 백준(Baekjoon)  (0) 2018.09.30
    1697번 백준(Baekjoon)  (0) 2018.09.24
    1929번 백준(Baekjoon)  (0) 2018.09.07
    1157번 백준(Baekjoon)  (0) 2018.09.06

    Comments