반응형
-문제
-코드
#include<stdio.h>
#include<queue>
#include<vector>
using namespace std;
int ch[100001];
int cal(int x, int i)
{
int res=0;
switch (i)
{
case 0:
res = x - 1;
break;
case 1:
res = x + 1;
break;
case 2:
res = x * 2;
break;
default:
break;
}
return res;
}
int main()
{
int n, k;
scanf("%d %d", &n, &k);
queue<int> q;
if (n == k)
{
printf("%d", 0);
return 0;
}
ch[n] = 1;
q.push(n);
while (!q.empty())
{
int tmp = q.front();
q.pop();
//printf("%d : %d\n", tmp, ch[tmp]);
for (int i = 0; i < 3; i++)
{
int pos = cal(tmp, i);
if (pos < 0 || pos > 100000) continue;
if (pos == k)
{
printf("%d", ch[tmp]);
return 0;
}
if (ch[pos] == 0)
{
ch[pos] = ch[tmp] + 1;
q.push(pos);
}
}
}
return 0;
}
반응형
'이론 > 코딩테스트' 카테고리의 다른 글
[백준] 2667번 단지번호붙이기 (BFS) (0) | 2022.07.30 |
---|---|
[백준] 2178번 미로 탐색 (BFS) (0) | 2022.07.30 |
[백준] 2467번 용액 (투포인터 알고리즘) (0) | 2022.07.30 |
[백준] 1940번 주몽 (투포인터 알고리즘) (0) | 2022.07.30 |
[백준] 2559번 수열 (투포인터 알고리즘) (0) | 2022.07.30 |