深搜广搜的队列写法模板
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
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
简历模版 把坐标放入队列,三种情况依次进队列
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
int book[1000010];
int n,k;
struct node
{
int x,step;
};
int cmp(int x)
{
if(x<0 || x>=1000000 || book[x])
return 0;
return 1;
}
int bfs(int x)
{
int i;
queue<node> Q;
node a,next;
a.x = x;
a.step = 0;
book[x] = 1;
Q.push(a);
while(!Q.empty())
{
a = Q.front();
Q.pop();
if(a.x == k)
return a.step;
next = a;
next.x = a.x+1;
if(cmp(next.x))
{
next.step = a.step+1;
book[next.x] = 1;
Q.push(next);
}
next.x = a.x-1;
if(cmp(next.x))
{
next.step = a.step+1;
book[next.x] = 1;
Q.push(next);
}
next.x = a.x*2;
if(cmp(next.x))
{
next.step = a.step+1;
book[next.x] = 1;
Q.push(next);
}
}
return -1;
}
int main()
{
int ans;
while(~scanf("%d%d",&n,&k))
{
memset(book,0,sizeof(book));
ans = bfs(n);
printf("%d\n",ans);
}
return 0;
}
农夫约翰得知一头逃犯奶牛的位置,他从点N出发,目标是点K,两者都在数轴上。约翰有两种移动方式:步行和瞬移。步行可以向左或向右移动1单位,瞬移可以将位置变为原来的2倍。如果奶牛不动,约翰如何最快抓住它?输入包含两个整数N和K,输出约翰抓到奶牛的最短时间。例如,当N=5, K=17时,最短路径5-10-9-18-17需要4分钟。"
132932429,20036702,SDIO总线在音视频设备中的应用解析,"['音视频开发', '接口标准', '数据传输', '嵌入式硬件']
1万+

被折叠的 条评论
为什么被折叠?



