Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 48127 | Accepted: 15077 |
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (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 points X - 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?
Input
Output
Sample Input
5 17
Sample Output
4
Hint
#include <iostream> #include <stdio.h> #include <string.h> #include <queue> #include <algorithm> using namespace std; int vis[101000], dis[101000]; int bfs(int n, int k) { queue<int>q; //简历队列 q.push(n); //将起点入队列 vis[n]=1; //标记起点被访问 dis[n]=0; //此时起点到自身的步数为0 int curpos; //当前节点 while(!q.empty() ) //判断队列不为空 { curpos=q.front(); //取出当前队首元素 q.pop(); if(curpos == k) //如果等于终点 { return dis[curpos]; //返回步数 } else { if(curpos-1>=0 && curpos<=100000 && vis[curpos-1]==0 ) //判断此点是否可行 { q.push(curpos-1); //如果行,进入队列 待命 vis[curpos-1]=1; //标记该点被访问,以后不要被重复访问了 dis[curpos-1]=dis[curpos]+1; // 到达此点的步数 == 当前点的步数+1 } if(curpos+1>=0 && curpos+1<=100000 && vis[curpos+1]==0 ) //类推 { q.push(curpos+1); vis[curpos+1]=1; dis[curpos+1]=dis[curpos]+1; } if(curpos*2>=0 && curpos*2<=100000 && vis[curpos*2]==0 ) //类推 { q.push(curpos*2); vis[curpos*2]=1; dis[curpos*2]=dis[curpos]+1; } } } return 0; } int main() { int n, k; while(scanf("%d %d", &n, &k)!=EOF) { memset(vis, 0, sizeof(vis)); memset(dis, 0, sizeof(dis)); printf("%d\n", bfs(n, k)); } return 0; }
第二次的写法:
#include <iostream> #include <string> #include <stdio.h> #include <string.h> #include <queue> #define INF 99999999 using namespace std; int vis[100001]; int dis[100001]; int bfs(int n, int k) { memset(vis, 0, sizeof(vis)); memset(dis, 0, sizeof(dis)); queue<int>q; q.push(n); vis[n]=1; dis[1]=0; int dd; while(!q.empty()) { dd=q.front(); q.pop(); if(dd==k) { return dis[dd]; } else { if( !vis[dd+1] && dd+1>=0 && dd+1<=100000 ) { q.push(dd+1); dis[dd+1]=dis[dd]+1; vis[dd+1]=1; } if( !vis[dd-1] && dd-1>=0 && dd-1<=100000 ) { q.push(dd-1); dis[dd-1]=dis[dd]+1; vis[dd-1]=1; } if(!vis[dd*2] && dd*2>=0 && dd*2<=100000 ) { q.push(dd*2); dis[dd*2]=dis[dd]+1; vis[dd*2]=1; } } } return 0; // 开始忘记 写这个指令了,跑出来的结果很像随机 结果! 不知道为什么,加上之后就运行正确了 ! }! int main() { int n, k; int dd; while(cin>>n>>k) { dd = bfs(n, k); cout<<dd<<endl; } return 0; }