标签:des style blog io os ar for strong sp
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; }
标签:des style blog io os ar for strong sp
原文地址:http://www.cnblogs.com/yspworld/p/4046684.html