Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
* Walking: FJ can move from any point X to the pointsX - 1 or X + 1 in a single minute* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Sample Input
5 17
Sample Output
4
思路:
由题意 , 特别明显的 , 用广度搜索来做 。
广度搜索: 1.将一个数压进栈去,取出栈首的元素,进行拓展(向前走一步,向后走一步,走到2*n的地方)
2.将拓展的元素压进栈里 , 同时 将首元素 删除 。
3.一直进行1,2 一直到搜索到为止。
Code:
#if 0 #include<iostream> #include<queue> using namespace std; queue <int> q; const int MAX = 100005 ; int ret[MAX]; bool pd[MAX]; int bfs(int m,int k) { if(m==k)return 0; //别忘记 这种情况 q.push(m); int cur; while(!q.empty()) { cur=q.front(); //取出 q.pop(); //删除 if(cur+1<MAX&&!pd[cur+1]) //进行拓展 { q.push(cur+1); ret[cur+1]=ret[cur]+1; pd[cur+1]=true; } if(cur+1==k)break; if(cur-1>=0&&!pd[cur-1]) { q.push(cur-1); ret[cur-1]=ret[cur]+1; pd[cur-1]=true; } if(cur-1==k)break; if(cur*2<MAX&&!pd[cur*2]) { q.push(cur*2); ret[cur*2]=ret[cur]+1; pd[cur*2]=true; } if(cur*2==k) break; } return ret[k]; } int main() { int M , K ; cin>>M>>K; cout<<bfs(M,K)<<endl; return 0; } #endif