백준

숨바꼭질 3

E재HO 2022. 8. 2. 16:52

숨바꼭질 3 성공

 
 
시간 제한메모리 제한제출정답맞힌 사람정답 비율
2 초 512 MB 48637 14225 9049 25.652%

문제

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 0초 후에 2*X의 위치로 이동하게 된다.

수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오.

입력

첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.

출력

수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.

예제 입력 1 복사

5 17

예제 출력 1 복사

2

힌트

수빈이가 5-10-9-18-17 순으로 가면 2초만에 동생을 찾을 수 있다.

출처

package practice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
	static int visited[] = new int[100001];
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		Arrays.fill(visited, -1);
		String s = in.readLine();
		String[] ss = s.split(" ");
		int start = Integer.parseInt(ss[0]);
		int end = Integer.parseInt(ss[1]);
		Queue<inq> queue = new LinkedList();
		
		
		visited[start]=0;
		queue.add(new inq(start, 0));
		while(!queue.isEmpty()) {
			
			int cur = queue.peek().cur;//위치
			int cnt = queue.peek().cnt;//시간
			queue.poll();
			if(cur*2<=100000) {
				if(visited[cur*2]>cnt ||visited[cur*2]==-1) {
					visited[cur*2]=cnt;
					queue.add(new inq(cur*2, cnt));		
				}
			}
			
			if(cur+1<=100000) {
				if(visited[cur+1]>cnt+1||visited[cur+1]==-1) {
					visited[cur+1]=cnt+1;
					queue.add(new inq(cur+1, cnt+1));
				}
			}
			
			if(cur-1>=0) {
				if(visited[cur-1]>cnt+1||visited[cur-1]==-1) {
					visited[cur-1]=cnt+1;
					queue.add(new inq(cur-1, cnt+1));
				}
			}
			
		}
		System.out.println(visited[end]);
	}	
	
	static class inq {
		public int cur=0;
		public int cnt=0;
		
		public inq(int cur, int cnt) {
			this.cur = cur;
			this.cnt = cnt;
		}
		
		
	}
}

범위 체크 잘해야함

0까지 탐색해야함