hdu2717

来源:互联网 发布:java中高级面试题大全 编辑:程序博客网 时间:2024/05/16 11:28

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (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 orX + 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 andK

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点,只能向左走一步,或者向右走一步,或者  
直接走n的2倍步,要求走最少的步数抓住站在k点的牛。  
  
#include<iostream>  #include<cstdio>  #include<cstring>  #include<queue>  using namespace std;  const int maxn = 200000 + 10;//因为可能是n*2大于100000;  bool used[maxn];//判断是否被访问过;  int n, m;  struct node  {      int n, x;  };  int bfs(int start)  {                  queue<node>q;      node temp;      memset(used, false, sizeof(used));      temp.n = start;      temp.x = 0;      used[start] = true;      q.push(temp);      while(!q.empty())      {          node type = q.front();          q.pop();          for(int i = 0; i < 3; i++)          {              node flag = type;              if(i == 0)              {                  flag.n = type.n + 1;              }              if(i == 1)              {                  flag.n = type.n - 1;              }              if(i == 2)             {                  flag.n =type.n * 2;              }              flag.x = type.x + 1;              if(flag.n >= 0 && flag.n <= 100000 && !used[flag.n])              {                  if(flag.n == m)                      return flag.x;                  used[flag.n] = true;                  q.push(flag);              }          }      }      }  int main()  {      while(scanf("%d%d", &n, &m)!=EOF)      {          if(n==m)//这一步一定要考虑;          {              printf("0\n");              continue;          }              printf("%d\n", bfs(n));      }  }  


0 0
原创粉丝点击