- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12851.java
More file actions
Latest commit
56 lines (42 loc) · 1.53 KB
/
Copy path12851.java
File metadata and controls
56 lines (42 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
importjava.util.*;
publicclassMain {
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
intn = sc.nextInt();
intk = sc.nextInt();
int[] map = newint[200002];
Queue<Integer> q = newLinkedList<>();
q.offer(n);
map[n] = 1;
intminCost = Integer.MAX_VALUE;
intcnt = 0;
while(!q.isEmpty()) {
intnow = q.poll();
// 다음 노드 방문비용이 찾아둔 최소비용을 넘어간다면 그만 끝내기
if(map[now] + 1 > minCost)
break;
// 최소비용을 찾은 경우 최초면 기록도 함
if(now == k) {
cnt++;
if(map[k] == 0)
minCost = map[now];
continue;
}
// 방문가능한 곳이고, 아직 방문을 안했거나 더 낮거나 같은 비용으로 방문할 수 있으면 방문
if(now+1 < 200002 && (map[now+1] == 0 || (map[now+1] != 0 && map[now]+1 <= map[now+1]))) {
map[now+1] = map[now] + 1;
q.offer(now+1);
}
if(now-1 >= 0 && (map[now-1] == 0 || (map[now-1] != 0 && map[now]+1 <= map[now-1]))) {
map[now-1] = map[now] + 1;
q.offer(now-1);
}
if(now*2 < 200002 && (map[now*2] == 0 || (map[now*2] != 0 && map[now]+1 <= map[now*2]))) {
map[now*2] = map[now] + 1;
q.offer(now*2);
}
}
System.out.println(map[k]-1);
System.out.println(cnt);
}
}