codeforces two buttons
import java.util.*; public class Main { static int[] vis = new int[100005]; static int[] dis = new int[100005]; static int n; static int m; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); if (n > m) { System.out.printf("%d%n", n-m); return; } Arrays.fill(vis, 0); Arrays.fill(dis, 0); bfs(); } public static void bfs() { Deque<Integer> que = new LinkedList<>(); // Deque是接口,既可以做为栈,又可以作为队列,取决于调用的API que.offer(n); vis[n] = 1; dis[n] = 0; while(!que.isEmpty()) { int tmp = que.poll(); if (tmp == m) { System.out.printf("%d%n", dis[tmp]); return ; } else { // n-1 if (tmp-1 > 0 && vis[tmp-1] == 0) { vis[tmp-1] = 1; que.offer(tmp-1); dis[tmp-1] = dis[tmp] + 1; } // n*2 if (tmp <= m && vis[tmp*2] == 0) { vis[tmp*2] = 1; que.offer(tmp*2); dis[tmp*2] = dis[tmp] + 1; } // n+1 if (tmp+1 <= m && vis[tmp+1] == 0) { vis[tmp+1] = 1; que.push(tmp+1); dis[tmp+1] = dis[tmp] + 1; } } } } }
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!