개발/알고리즘

백준 13549번 : 숨바꼭질3

라사 RASA 2020. 10. 11. 15:20
// 0, 1 이기에 먼저 찾아낸 게 무조건 빠름.

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int N, K;
vector<int> dist(100001, 100001);
priority_queue<pair<int,int>> q;

void approach(int pos)
{
	dist[pos] = 0;
	q.push({0, pos});
	
	while(!q.empty())
	{
		int nextTime;
		int here = q.top().second;
		int weight = -q.top().first;
		q.pop();
		
		if(here == K)
			break;
		
		if(dist[here] < weight)
			continue;
		
		if(here > 0)
		{
			nextTime = weight + 1;
		
			if(nextTime < dist[here-1])
			{
				dist[here-1] = nextTime;
				q.push({-nextTime, here-1});
			}
		}
		
		if(here < 100000)
		{
			nextTime = weight + 1;

			if(nextTime < dist[here+1])
			{
				dist[here+1] = nextTime;
				q.push({-nextTime, here+1});
			}
			
			if(here < 50001)
			{
				nextTime = weight;

				if(nextTime < dist[here*2])
				{
					dist[here*2] = nextTime;
					q.push({-nextTime, here*2});
				}
			}		
		}
	}
}

int main(void)
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	
	cin>>N>>K;
	
	approach(N);
	
	cout<<dist[K]<<'\n';
}