题目描述:
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
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
题意:
给定两个整数n和k
通过 n+1或n-1 或n*2 这3种操作,使得n==k
输出最少的操作次数
解题思路:
- 因为是找最少的操作次数,所以选用bfs搜索
- 其实就是道水题,哈哈,但这是我做出来的第一道 bfs
- 坑点就是这道题如果输入0,会出现负数,然后标记的时候mark[负数] = 1;想想就好笑。在这里Re了10多发,很崩溃。所以记得处理负数,短路掉。还有就是标记数组要开的比题目的最大范围大二倍,因为有n*2的操作。
对于bfs的理解:
- bfs是一层一层的访问
- 通过队列暂存每一层的节点,就可以做到按层访问。
- 还有就是一定要对访问过的元素做标记,标记的元素就不再访问,不然会重复访问。
预备知识:
使用队列要加的头文件:# inlcude <queue>
queue<int> q; // 定义一个存储int型数据的队列,int可以换成其他数据结构
q.push(tem); //将tem放入到队列中
q.front(); // 返回首个元素
q.pop(); //删除首个元素
# include <cstdio>
# include <queue>
# include <cstring>
using namespace std;
typedef pair<int ,int> P;
int mark[200030]; //标记元素是否已经用过
queue<P> q;
int bfs(int n,int k)
{
memset(mark,0,sizeof(mark)); //初始化为0,表示未用过
int cnt = 0;
q.push(P(0,n));
while(q.size()){ // 当队列不为空时循环
P tem = q.front();
q.pop();
if(tem.second == k) // 如果已经相等,记录下步数,跳出循环
{
cnt = tem.first;
break;
}
if(tem.second*2 > 200001 || tem.second < 0) //如果是负数跳过
continue;
// printf("%d\n",tem.second);
if(mark[tem.second+1] == 0) //判断每种操作后的数是否已经访问过
{
mark[tem.second+1] = 1;
q.push(P(tem.first+1,tem.second+1));
}
if(mark[tem.second-1] == 0)
{
mark[tem.second-1] = 1;
q.push(P(tem.first+1,tem.second-1));
}
if(mark[tem.second*2] == 0)
{
mark[tem.second*2] = 1;
q.push(P(tem.first+1,tem.second*2));
}
}
return cnt;
}
int main()
{
int n,k;
while(scanf("%d %d",&n,&k) != EOF)
{
printf("%d\n",bfs(n,k));
}
return 0;
}