码迷,mamicode.com
首页 > 其他好文 > 详细

poj3278 bfs

时间:2018-01-07 15:53:31      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:and   ems   strong   pre   std   art   orm   width   inpu   

                                                     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

标签:and   ems   strong   pre   std   art   orm   width   inpu   

原文地址:https://www.cnblogs.com/carcar/p/8227878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!