Posts 13549 숨바꼭질 3
Post
Cancel

13549 숨바꼭질 3

13549 숨바꼭질 3

알고리즘(BFS)

1
1. BFS로 가능한 곳은 가되, check엔 이전에 온 것보다 적은 시간을 걸리며 온 것을 받아주기 위해 시간을 저장하자.

코드

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <cstring>
#include <list>

using namespace std;

int N, K, result = 2000000000;
int check[200020];
list<pair<int,int>> q;

int bfs();
int min(int a, int b) {
	return a < b ? a : b;
}

int main() {
	for (int i = 0; i < 200020; i++)
		check[i] = 2000000000;

	cin >> N >> K;
	if (N >= K)
		cout << N - K;
	else
		cout << bfs() << endl;

}

int bfs() {
	q.push_back({ N, 0 });
	check[N] = 0;

	while (!q.empty()) {
		int X = q.front().first, t = q.front().second;
		q.pop_front();

		if (X >= K) {
			result = min(result, X - K + t);
		}
		else {
			if (X != 0 && t < check[X * 2]) {
				q.push_back({ X * 2, t });
				check[X * 2] = t;
			}
			if (t + 1 < check[X + 1]) {
				q.push_back({ X + 1, t + 1 });
				check[X + 1] = t + 1;
			}
			if (X-1 >= 0 && t + 1 < check[X - 1]) {
				q.push_back({ X - 1, t + 1 });
				check[X - 1] = t + 1;
			}
		}
	}
	return result;
}
This post is licensed under CC BY 4.0 by the author.

13458 Samsung sw test

14003 LIS5

Comments powered by Disqus.