HDU 2717 Catch That Cow

典型的BFS题,这里要注意的就是边界条件,就是2*X不要超过人与牛的距离绝对值之差加上牛的距离,应为超过就没意义了,因为最长时间为人与牛的距离绝对值之差;

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct T
{
    int place,time;       
}q[200000];
int hash[200024];
int BFS( int pointA,int pointB )
{
    int number=abs( pointA-pointB );
    memset( hash,0,sizeof( hash ) );
    hash[pointA]=1;
    int first=0,end=0;
    T t;
    t.place=pointA;
    t.time=0;
    q[end++]=t;
    while( first<end )
    {
        int x=q[first].place+1;   
        if( !hash[x]&&x<=pointB )
        {
            hash[x]=1;
            t.place=x;
            if( x==pointB )
               return q[first].time+1;
            t.time=q[first].time+1;
            q[end++]=t; 
        }
        x=q[first].place-1;   
        if( x>=0&&!hash[x] )
        {
            hash[x]=1;
            t.place=x;
            if( x==pointB )
               return q[first].time+1;
            t.time=q[first].time+1;
            q[end++]=t; 
        }
        x=q[first].place*2;
        if( x<(pointB+number)&&!hash[x] )
        {
            hash[x]=1;
            t.place=x;
            if( x==pointB )
               return q[first].time+1;
            t.time=q[first].time+1;
            q[end++]=t;    
        } 
        first++;    
    }
    return number;    
}
int main()
{
    int pointA,pointB;
    while( scanf( "%d%d",&pointA,&pointB )!=EOF )
    {
        if( pointA==pointB )  printf( "0\n" );
        else
            printf( "%d\n",BFS( pointA,pointB ) );       
    }
    return 0;    
}

 

posted @ 2011-11-19 09:26  wutaoKeen  阅读(342)  评论(0)    收藏  举报