숨바꼭질
시간 제한 | 메모리 제한 | 제출 | 정답 | 맞은 사람 | 정답 비율 |
---|---|---|---|---|---|
2 초 | 128 MB | 50842 | 14008 | 8681 | 24.683% |
문제
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 1초 후에 2*X의 위치로 이동하게 된다.
수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오.
입력
첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.
출력
수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.
오늘도 배열크기 잘못줘서 틀렸다. 100000도 포함되는 배열을 만들었어야했는데..
그것만 빼면 구현 까지는 너무 쉬운문제 (최적화는 ..... ㅠ)
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
bool visited[100001];
int n,k;
queue<int> que;
int cnt=0;
void bfs();
int main(){
freopen("input.txt","r",stdin);
memset(visited, false, sizeof(visited));
cin>>n>>k;
while(!que.empty()) { que.pop(); }
que.push(n);
visited[n]= true;
bfs();
cout<<cnt-1;
return 0;
}
void bfs(){
int temp;
int width_len=que.size();
while( !que.empty() ){
temp=0;
cnt++;
for(int i=0; i<width_len; ++i){
n= que.front();
//cout<<que.front()<<" ";
que.pop();
if( n == k ){
return;
}
if( n-1 >= 0 && !visited[n-1]){ //1뺄때
que.push(n-1);
visited[n-1]= true;
temp++;
}
if( n*2 < 100001 && !visited[n*2]){ //2배할때
que.push(n*2);
visited[n*2]= true;
temp++;
}
if( n+1 < 100001 && !visited[n+1]){ //1더할때ac
que.push(n+1);
visited[n+1]= true;
temp++;
}
}
width_len=temp;
}
}