poj3278 bfs

Posted carcar

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj3278 bfs相关的知识,希望对你有一定的参考价值。

                                                     Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 102339   Accepted: 31988

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 - 1 or + 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
 
 
 
 
这是一道入门级的bfs搜索题,下面的注释很详细
 
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 long long  n,k,x;//n起点,k终点,x中间变量
 5 long long bo[100010],len[100010],que[100010];//bo标记点,一个点只能访问一次,len距离,que存队列
 6 long long front,sear,i;//front队列读取位置,队列填入的位置
 7 long long bfs()
 8 {
 9          if(n==k)return 0;//起点与终点相同
10          memset(bo,0,sizeof(bo)); //将所有点都标记为未访问
11          front=0;sear=0;//读取了0个点 填入完了1个
12          que[0]=n;len[0]=0;bo[n]=1;//填入一个点,长度为0,访问过起点
13          while(front<=sear)//访问的点超过写入点就结束
14          {
15              for(i=0;i<3;i++)//三个方向
16              {
17                  if(i==0) x=que[front]-1;
18                  else if(i==1) x=que[front]+1;
19                  else if(i==2) x=2*que[front];
20                  if(x>=0&&x<=100000&&bo[x]==0)
21                  {
22                      bo[x]=1;//标记访问
23                      len[++sear]=len[front]+1;//为上个点长度加一
24                      que[sear]=x;//写入队列
25                      if(x==k)return len[sear];//找到了点
26                  }
27              }
28            front++;//访问下一个队列中的点
29          }
30     return -1;
31 }
32 int main()
33 {
34     while(scanf("%lld %lld",&n,&k)==2)
35          printf("%lld\n",bfs());
36     return 0;
37 }

 

以上是关于poj3278 bfs的主要内容,如果未能解决你的问题,请参考以下文章

POJ 3278 - Catch That Cow - [BFS]

POJ 3278 Catch That Cow(模板——BFS)

poj3278 bfs

超超超简单的bfs——POJ-3278

poj 3278 Catch That Cow bfs

POJ 3278 Catch That Cow(bfs)