반응형
거의 유사한 문제(숨바꼭질2): https://fishersheep.tistory.com/188
백준 12851 숨바꼭질2 c++ 주석포함
#include #include #include #include using namespace std; int n, k; int sec=0; //가장빠른시간을 저장할 변수 bool visited[100001]; //방문여부를 저장할 배열 int cnt = 0; //빠른시간으로 동생을 찾는 방법..
fishersheep.tistory.com
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
int n, k;
bool visited[100001];
int result=0;
void bfs()
{
queue < pair<int, int>>q;
q.push(make_pair(n, 0));
visited[n] = true;
while (!q.empty())
{
int a = q.front().first;
int b = q.front().second;
q.pop();
visited[a] = true;
if (a == k && result == 0)
{
result = b;
}
else if (a == k && result != 0)
result = min(result, b); //기존의 시간과 비교했을때 더 작은 값을 result에 저장
if (a + 1 <= 100001 && visited[a + 1] != true)
q.push(make_pair(a + 1, b + 1));
if (a - 1 >= 0 && visited[a - 1] != true)
q.push(make_pair(a - 1, b + 1));
if (a * 2 <= 100001 && visited[a *2] != true)
q.push(make_pair(a * 2, b)); //순간이동을 하는경우 0초 이기때문에 시간 증가 X
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> k;
bfs();
cout << result;
return 0;
}
반응형
'Programming > Baekjoon' 카테고리의 다른 글
백준 9613 GCD합 [c++] (0) | 2022.02.08 |
---|---|
백준 13913 숨바꼭질 4 [c++] (0) | 2022.02.07 |
백준 12851 숨바꼭질2 c++ 주석포함 (0) | 2022.02.06 |
백준 16953 c++ 주석포함 (0) | 2022.02.05 |
백준 2606 c++ 주석포함 (0) | 2022.02.05 |