hdu 2717
地址:http://acm.hdu.edu.cn/showproblem.php?pid=2717
题意:在x坐标上,农夫在n,牛在k。农夫每次可以移动到n-1, n+1, n*2的点。求最少到达k的步数。
mark:bfs。范围是2*k内。因为如果当前点大于k,执行2*n和n+1的操作都不是最佳选择。
代码:
1 # include <stdio.h> 2 # include <string.h> 3 4 5 int vis[200010] ; 6 int q[200010] ; 7 8 9 int bfs (int n, int k) 10 { 11 int f = 0, r = 1 ; 12 int nn ; 13 q[0] = n, vis[n] = 0 ; 14 while (f != r) 15 { 16 n = q[f++] ; 17 if (n==k) return vis[n] ; 18 19 nn = n+1 ; 20 if (nn <= 2*k && vis[nn]==-1) vis[nn] = vis[n]+1, q[r++] = nn ; 21 22 nn = n-1 ; 23 if (nn >= 0 && vis[nn] == -1) vis[nn] = vis[n]+1, q[r++] = nn ; 24 25 nn = n*2 ; 26 if (nn <= 2*k && vis[nn] == -1) vis[nn] = vis[n]+1, q[r++] = nn ; 27 } 28 return -1 ; 29 } 30 31 32 int main () 33 { 34 int n, k ; 35 while (~scanf ("%d%d", &n, &k)) 36 { 37 memset (vis, -1, sizeof(vis)) ; 38 printf ("%d\n", bfs(n, k)) ; 39 } 40 return 0 ; 41 }