File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+ public static void main (String [] args ) throws Exception {
7+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
8+ StringTokenizer st = new StringTokenizer (br. readLine());
9+
10+ int n = Integer . parseInt(st. nextToken());
11+ int k = Integer . parseInt(st. nextToken());
12+
13+ if (n >= k) {
14+ System . out. print(n- k);
15+ return ;
16+ }
17+
18+ Deque<Integer > dq = new ArrayDeque<> ();
19+ int [] time = new int [100001 ];
20+ Arrays . fill(time, Integer . MAX_VALUE );
21+ time[n] = 0 ;
22+ dq. add(n);
23+
24+ while (! dq. isEmpty()){
25+ int cur = dq. pollFirst();
26+
27+ if (cur == k) {
28+ System . out. println(time[cur]);
29+ return ;
30+ }
31+
32+ int next = cur * 2 ;
33+ if (next <= 100000 && time[next] > time[cur]) {
34+ time[next] = time[cur];
35+ dq. addFirst(next);
36+ }
37+
38+ next = cur - 1 ;
39+ if (next >= 0 && time[next] > time[cur] + 1 ) {
40+ time[next] = time[cur] + 1 ;
41+ dq. addLast(next);
42+ }
43+
44+ next = cur + 1 ;
45+ if (next <= 100000 && time[next] > time[cur] + 1 ) {
46+ time[next] = time[cur] + 1 ;
47+ dq. addLast(next);
48+ }
49+ }
50+ }
51+ }
52+ ```
You can’t perform that action at this time.
0 commit comments