백준 16953
n이 최대 10억까지 가능 하기 때문에 vis 배열을 두기엔 불가능
=> map을 이용! 메모리적으로 유리
map 배열 대신 쓸 수 도 있음 (배열의 크기가 말도 안되게 클 때)
#include<iostream>
#include<string>
#include<queue>
#include<map>
using namespace std;
int a, b;
map<long long, int> vis;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cin >> a >> b;
queue<pair<long long, int>>q;
q.push({ a,0 });
int cnt = 0;
vis[a] = 1;
while (!q.empty()) {
auto cur = q.front();
q.pop();
if (cur.first == b) {
cout << cur.second+1 << '\n';
return 0;
}
for (int i = 0; i < 2; i++) {
long long nxt;
if (i == 0) {
nxt = cur.first * 2;
}
else {
nxt = cur.first * 10 + 1;
}
if (nxt <= 0 || nxt > 1000000000) continue;
if (vis[nxt]) continue;
q.push({ nxt,cur.second + 1 });
vis[nxt] = 1;
}
}
cout << -1 << '\n';
}