백준 / 16953 / A → B / C++

비니01·2024년 8월 13일

백준

목록 보기
14/49

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

#include <bits/stdc++.h>

using namespace std;

long long int ans = INT_MAX;
long long int n;

void bfs(long long int val)
{
    queue<pair<long long int,long long int>> Q;
    Q.push({val,1});
    while(!Q.empty())
    {
        pair<long long int,long long int> cur = Q.front();
        Q.pop();
        if(cur.first == n)
        {
            ans = min(ans,cur.second);
        }
        else if(cur.first > n)
        {
            continue;
        }
        else
        {
            Q.push({cur.first * 10 + 1,cur.second + 1});
            Q.push({cur.first * 2,cur.second + 1});
        }
    }
    return;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    //freopen("test.txt", "rt", stdin);
    long long int start;
    cin >> start >> n;
    bfs(start);
    if(ans == INT_MAX)
    {
        cout << -1;
    }
    else
    {
        cout << ans;
    }
    return 0;
}

BFS로 풀되, 수가 증가하기만 하고 n 10 + 1 혹은 n 2의 값으로만 증가하기에 visited를 선언해서 중복 체크를 할 필요는 없어 보였다.

근데 또 int / long long int 때문에 두번 틀렸다. 구상 자체에는 문제가 없었는지 AC를 받았다.

profile
이것저것

0개의 댓글