수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 0초 후에 2*X의 위치로 이동하게 된다.
수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오.
첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.
수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.
5 17
2
간단한 BFS 문제!
다익스트라 알고리즘으로도 풀 수 있다고 하던데 나는 bfs가 더 간단해보여서 BFS로 풀어봤다.
start에서 goal로 가는 경로 중 가중치 합이 가장 작은 길을 찾으면 된다. x2를 하는 경로는 가중치가 0, +1 혹은 -1을 하는 경로는 가중치가 1인 경로이다. 일반 BFS처럼 풀면 가중치가 서로 달라서 풀 수 없기 때문에, 우선순위 큐를 이용하였다.
pair를 만들어서 다음 위치의 가중치 합과 다음 위치를 같이 우선순위 큐에 넣어주었다. 가중치 합이 작은 경로부터 모두 탐색하므로 목표 지점을 발견하였을 때 목표 지점까지의 가중치 합이 최소 가중치 합이 된다.
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
void input_data(void);
int find_min(void);
int start, goal;
int is_visited[100001];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> p_queue;
int main(void)
{
input_data();
cout << find_min();
return (0);
}
void input_data(void)
{
cin >> start >> goal;
fill(is_visited, is_visited + 100001, 0);
return ;
}
int find_min(void)
{
p_queue.push(make_pair(0, start));
is_visited[start] = 1;
while (!p_queue.empty())
{
int now_sec = p_queue.top().first;
int now_location = p_queue.top().second;
int next_location;
p_queue.pop();
//cout << now_location << ' ' << now_sec << '\n';
if (now_location == goal)
return (now_sec);
next_location = now_location * 2;
if (next_location <= 100000 && is_visited[next_location] == 0)
{
p_queue.push(make_pair(now_sec, next_location));
is_visited[next_location] = 1;
}
next_location = now_location + 1;
if (next_location <= 100000 && is_visited[next_location] == 0)
{
p_queue.push(make_pair(now_sec + 1, next_location));
is_visited[next_location] = 1;
}
next_location = now_location - 1;
if (next_location >= 0 && is_visited[next_location] == 0)
{
p_queue.push(make_pair(now_sec + 1, next_location));
is_visited[next_location] = 1;
}
}
return (-1);
}
성공!😍😍