티스토리 뷰


[ 해결 방법 ]

단순 BFS 문제이다. 현재 수빈이의 위치에서 갈 수 있는 방향(X+1, X-1, 2*X)을 큐에 넣고 K가 나올 때까지 계속 반복하면 된다.


[ 코드 ]

#include <iostream>
#include <queue>
using namespace std;
struct pos
{
int x, t;
};
int N, K, Max;
queue<pos> q;
bool visit[200001];
int dir[3] = { -1,1,1 };
int main()
{
cin >> N >> K;
if (N == K)
{
cout << "0" << endl;
return 0;
}
else if (K > N)
Max = 2 * K;
else
Max = N;
q.push(pos{ N, 0 });
visit[N] = true;
pos cur, next;
while (!q.empty())
{
cur = q.front();
q.pop();
dir[2] = cur.x;
for (int i = 0; i < 3; i++)
{
next.x = cur.x + dir[i];
next.t = cur.t + 1;
if (next.x == K)
{
cout << next.t << endl;
return 0;
}
if (next.x < 1 || next.x > Max)
continue;
if (visit[next.x] == false)
{
visit[next.x] = true;
q.push(next);
}
}
}
return 0;
}


'알고리즘 > 너비우선탐색(BFS)' 카테고리의 다른 글

너비우선탐색 BFS (백준-바이러스)  (0) 2016.12.20
백준_스타트링크  (0) 2016.09.08
백준_트리의 지름길  (0) 2016.09.03
백준_다리 만들기  (1) 2016.07.11
백준_이분 그래프  (0) 2016.07.08
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함