本题大意:一个农夫和一头牛在一个数轴上,牛不动,农夫每次可使自己的坐标 +1 , -1, *2 ,问最小需要多少次农夫与牛坐标相等。
本题思路:最短路,BFS。
本题代码:

1 #include <cstdio> 2 #include <cstring> 3 #include <map> 4 #include <queue> 5 using namespace std; 6 7 int n, k, ans; 8 const int maxn = 1e5 + 5, INF = -1; 9 int step[maxn]; 10 bool vis[maxn]; 11 int bfs() { 12 int now, Next; 13 queue <int> s; 14 s.push(n); 15 step[n] = 0; 16 vis[n] = true; 17 while(!s.empty()) { 18 now = s.front(); 19 s.pop(); 20 for(int i = 0; i < 3; i ++) { 21 if(i == 0) 22 Next = now - 1; 23 else if(i == 1) 24 Next = now + 1; 25 else 26 Next = now * 2; 27 if(Next < 0 || Next >= maxn) continue; 28 if(!vis[Next]) { 29 step[Next] = step[now] + 1; 30 s.push(Next); 31 vis[Next] = true; 32 } 33 if(Next == k) return step[Next]; 34 } 35 } 36 return -1; 37 } 38 39 int main () { 40 memset(vis, false, sizeof(vis)); 41 memset(step, 0, sizeof(step)); 42 scanf("%d %d", &n, &k); 43 ans = bfs(); 44 printf("%d ", ans); 45 return 0; 46 }