- ์ด ๊ธ์ c++๋ก ํ์ด๋ฅผ ์์ฑํ์์ต๋๋ค.
๋ฌธ์
ํ์ด
- BFS๋ฅผ ํ์ฉํ๋ ๋ฌธ์ ์ธ๋ฐ 2์ฐจ์์ด ์๋ 1์ฐจ์์ผ๋ก ์์ฑํ๋ฉด ๋ฉ๋๋ค.
#include<iostream>
#include<queue>
using namespace std;
int arr[100005];
int main(){
int n,k;
cin>>n>>k;
queue<int> q;
arr[n] = 1;
q.push(n);
while(!q.empty()){
int cur = q.front();
if(cur == k) break;
q.pop();
if(cur>0 && arr[cur-1] == 0){
q.push(cur-1);
arr[cur-1] = arr[cur]+1;
}
if(cur<100000 && arr[cur+1] == 0){
q.push(cur+1);
arr[cur+1] = arr[cur]+1;
}
if(cur<=50000 && arr[2*cur] == 0){
q.push(2*cur);
arr[2*cur] = arr[cur]+1;
}
}
cout<<arr[k]-1;
}
- ์ถ๊ฐ๋ก ๊ถ๊ธํ ์ ์ด๋ ์์ ํ ๋ถ๋ถ ์์ผ๋ฉด ๋๊ธ๋ก ๋จ๊ฒจ์ฃผ์ธ์.