Catch That Cow(捉住那头牛)

poj 3278 

题目大意:给出坐标中人的位置和牛的位置,然后牛不动,让你按照给定的策略(走一秒,退一退,走二倍当前的时间)去到牛的身边,求最小步子数

解决:DFS,分析若一开始牛在人的身后,只有往后退的份了,所以加一个判断条件最好

#include <iostream>
#include <queue>
using namespace std;
int n,k;
struct node
{
  int pos,step;
  node(int p,int s){pos=p;step=s;}
  node(){}
};
bool inq[200005];
int  bfs()
{
    node t;
    queue<node> q;
    q.push( node(n,0) );
    inq[n]=1;
    while( !q.empty() )
    {
        t = q.front();
        q.pop();
       //首先判断扩展出的新节点有没有符合要求的 ,即有没到牛身边了 
        if(t.pos+1 == k || t.pos-1 == k || t.pos*2 == k)return t.step+1;
     //没有的时候,就剪枝入队
        if(t.pos + 1 < k && !inq[t.pos + 1] )
        {
            inq[t.pos + 1]=1;
            q.push( node(t.pos+1,t.step+1) );
        }
        if( t.pos -1 >=0 && !inq[t.pos - 1] )
        {
            inq[t.pos - 1]=1;
            q.push( node(t.pos - 1,t.step+1) );
        }
        if( t.pos * 2 < 2 * k && !inq[ t.pos * 2 ])
        {
            inq[t.pos * 2]=1;
            q.push( node(t.pos * 2,t.step+1 ));
        }
    }
}
int main()
{
    //题目中没说多组测试数据可以按照一组处理
     cin>>n>>k;
    //首先判断牛与人的位置
     if(n >= k)cout<<n-k<<endl;
      else cout<<bfs()<<endl;
     system( "pause" );
    return 0;
}

原文地址:https://www.cnblogs.com/hpustudent/p/2166033.html