import java.util.HashSet; import java.util.linkedList; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int res = solve(n, m); System.out.println(res); } public static int solve(int n, int m) { //特殊情况判断 if (n == 1 && m == 1) return 0; if (n >= m) { return n - m; } linkedListqueue = new linkedList<>(); Set set = new HashSet<>(); queue.offer(new int[]{n, 0}); set.add(n); while (!queue.isEmpty()) { int[] cur = queue.poll(); int num = cur[0]; int step = cur[1]; if (num == m) { return step; } if (!set.contains(num - 1)) { set.add(num - 1); queue.offer(new int[]{num - 1, step + 1}); } if (num < m && !set.contains(num * 2)) { set.add(num * 2); queue.offer(new int[]{num * 2, step + 1}); } } return -1; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)