C - Catch That Cow

题目大意
农民约翰需要抓住他的牛,他和他的牛在一条直线上(估计是一维生物),约翰在N N  (0 ≤  N  ≤ 100,000) 处,他的牛在   K  (0 ≤  K  ≤ 100,000) ,约翰下次可以移动到x+1或者x-1或者2*x的地方,问约翰最少需要多少步才能找到他的牛。

也是非常非常水的题目,求最快当然是用广搜...

//////////////////////////////////////////////////////////////

#include<stdio.h>
#include< string.h>
#include<queue>
using  namespace std;

#define maxn 100001

int v[maxn]; // 标记是否走过,防止重走

int BFS( int s,  int e)
{
    queue< int> Q;

    Q.push(s);
    v[s] =  1;

     while(Q.size())
    {
        s = Q.front();
        Q.pop();

         if(s == e)
             return v[s]- 1;

         for( int i= 0; i< 3; i++)
        {
             int q=s;

             if(i ==  0)
                q--;
             else  if(i ==  1)
                q++;
             else
                q *=  2;

             if(q>= 0 && q <=maxn && v[q] ==  0)
            {
                Q.push(q);
                v[q] = v[s]+ 1;
            }
        }
    }

     return - 1;
}

int main()
{
     int s, e;

     while(scanf( " %d%d ", &s, &e) != EOF)
    {
        memset(v,  0sizeof(v));

         int ans = BFS(s, e);

        printf( " %d\n ", ans);
    }

     return  0;

} 

你可能感兴趣的:(catch)