博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PoJ3278--Catch That Cow(Bfs)
阅读量:7014 次
发布时间:2019-06-28

本文共 2335 字,大约阅读时间需要 7 分钟。

Catch That Cow

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 61317   Accepted: 19155

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

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.

Source

 
 
RE: 坐标轴上有两个点(a、b), 求 a 接近 b 所需走的最小步数;
  有三种走法,(x-1)、 (x+1)、(2*x);
  a > b  → → 输出;
  else :: Bfs;
  
1 #include 
2 #include
3 #include
4 #include
5 using namespace std; 6 7 const int maxn = 100000 + 5; 8 int vis[maxn], cnt[maxn]; 9 queue
q;10 11 void Bfs()12 {13 int nx;14 while(!q.empty())15 {16 int x = q.front(); q.pop();17 for(int i = 0; i < 3; i++) //三种走法; 18 {19 if(i == 0) nx = x + 1;20 else if(i == 1) nx = x - 1;21 else nx = 2 * x;22 if(nx >= 0 && nx <= 100000 && !vis[nx]) //遍历到最后找最优?::剪枝? 23 {24 vis[nx] = 1;25 cnt[nx] = cnt[x] + 1;26 q.push(nx); 27 } 28 } 29 }30 }31 32 int main()33 {34 int m, n;35 while(~scanf("%d %d", &m, &n))36 {37 if(m > n)38 {39 printf("%d\n", m - n);40 return 0;41 }42 memset(vis, 0, sizeof(vis));43 vis[m] = 1;44 cnt[m] = 0;45 q.push(m);46 Bfs();47 printf("%d\n", cnt[n]);48 } 49 return 0;50 }

 

 

 
  

转载于:https://www.cnblogs.com/soTired/p/4708873.html

你可能感兴趣的文章