
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static class Node implements Comparable<Node> {
int pos;
int time;
Node(int p, int t) {
this.pos = p;
this.time = t;
}
@Override
public int compareTo(Node o) {
return this.time - o.time;
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int min = Integer.MAX_VALUE;
boolean[] visited = new boolean[100001];
PriorityQueue<Node> queue = new PriorityQueue<>();
queue.add(new Node(N, 0));
while (!queue.isEmpty()) {
Node cur = queue.poll();
int cur_pos = cur.pos;
int cur_time = cur.time;
if (visited[cur_pos]) {
continue;
}
visited[cur_pos] = true;
if (cur_pos == K) {
min = cur_time;
break;
}
int next_pos;
next_pos = cur_pos - 1;
if (next_pos >= 0 && !visited[next_pos]) {
queue.add(new Node(next_pos, cur_time + 1));
}
next_pos = cur_pos + 1;
if (next_pos <= 100000 && !visited[next_pos]) {
queue.add(new Node(next_pos, cur_time + 1));
}
next_pos = cur_pos * 2;
if (next_pos <= 100000 && !visited[next_pos]) {
queue.add(new Node(next_pos, cur_time));
}
}
bw.write(min + "\n");
bw.close();
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 15686번: 치킨 배달 (0) | 2025.04.25 |
|---|---|
| [JAVA-자바] 11003번: 최솟값 찾기 (0) | 2025.04.24 |
| [JAVA-자바] 12865번: 평범한 배낭 (0) | 2025.04.23 |
| [JAVA-자바] 9251번: LCS (0) | 2025.04.23 |
| [JAVA-자바] 2096번: 내려가기 (0) | 2025.04.20 |