fork download
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Edge implements Comparable<Edge>{
  5. int end;
  6. int value;
  7.  
  8. Edge(int end, int value) {
  9. this.end = end;
  10. this.value = value;
  11. }
  12. public int compareTo(Edge o) {
  13. return this.value - o.value;
  14. }
  15. }
  16.  
  17. public class Main {
  18. public static void main(String[] args) throws IOException {
  19. StringTokenizer st = new StringTokenizer(br.readLine());
  20. int N = Integer.parseInt(st.nextToken());
  21. int K = Integer.parseInt(st.nextToken());
  22. int num = Math.max(N,K);
  23.  
  24. ArrayList<Edge>[] list = new ArrayList[num*2+1];
  25. int[] distance = new int[num*2+1];
  26. boolean[] check = new boolean[num*2+1];
  27.  
  28. for(int i = 0; i<=num*2; i++) {
  29. list[i] = new ArrayList<>();
  30. }
  31. Arrays.fill(distance,Integer.MAX_VALUE);
  32. list[0].add(new Edge(1,1));
  33.  
  34. for(int i = 1; i<=num*2; i++) {
  35. list[i].add(new Edge(i-1,1));
  36. list[i].add(new Edge(i+1,1));
  37. list[i].add(new Edge(i*2,1));
  38. }
  39.  
  40. distance[N] = 0;
  41.  
  42. PriorityQueue<Edge> queue = new PriorityQueue<>();
  43. queue.add(new Edge(N,0));
  44. int[] route = new int[num+1];
  45.  
  46. while(!queue.isEmpty()) {
  47. Edge a = queue.poll();
  48. if(check[a.end])
  49. continue;
  50.  
  51. check[a.end] = true;
  52. for(Edge o : list[a.end]) {
  53. if(o.end > num || o.end<0)
  54. continue;
  55.  
  56. if(distance[o.end] > distance[a.end] + o.value) {
  57. distance[o.end] = distance[a.end] + o.value;
  58. queue.add(new Edge(o.end, distance[o.end]));
  59. route[o.end] = a.end;
  60. }
  61. }
  62. }
  63. System.out.println(distance[K]);
  64.  
  65. int tmp = K;
  66. Stack<Integer> stack = new Stack<>();
  67. while(true) {
  68. stack.push(tmp);
  69. tmp = route[tmp];
  70. if(tmp==0)
  71. break;
  72. }
  73. if(N!=K && N==0)
  74. stack.push(0);
  75.  
  76. while(!stack.isEmpty())
  77. System.out.print(stack.pop() + " ");
  78. System.out.println("");
  79. }
  80. }
Success #stdin #stdout 0.12s 36028KB
stdin
4 7
stdout
3
4 3 6 7