반응형
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 | #include <iostream> #include <queue> using namespace std; int n, k, cnt; bool visited[200001]; queue<int> q; bool valid(int x) { if (x >= 0 && x <= 100000) return true; return false; } void insert(int x) { if (!valid(x)) return; if (!visited[x]) { q.push(x); visited[x] = 1; } } void teleport(int n) { // 순간이동 할 수 있는 위치 (n*2) 모두 삽입 if (!valid(n)) return; for (int i = n; i <= 100000; i *= 2) { if (!visited[i]) { q.push(i); visited[i] = 1; } if (i == 0) break; // 0일 때 순간이동 못함 -> 무한루프 } } void bfs(int n) { teleport(n); while (!q.empty()) { int size = q.size(); while (size--) { int now = q.front(); q.pop(); if (now == k) { cout << cnt; return; } insert(now - 1); // 앞으로 이동 insert(now + 1); // 뒤로 이동 teleport(now - 1); // 앞에서 순간이동 할 수 있는 위치 모두 삽입 teleport(now + 1); // 뒤에서 순간이동 할 수 있는 위치 모두 삽입 } cnt++; } } int main() { cin >> n >> k; bfs(n); } | cs |
반응형
'백준 > DFS, BFS' 카테고리의 다른 글
백준 16947 [복습 필수] (0) | 2021.03.06 |
---|---|
백준 16197 (0) | 2021.02.23 |
백준 14226 [복습 필수] (0) | 2021.02.19 |
백준 13913 (0) | 2021.02.19 |
백준 2178 (0) | 2021.02.19 |