HDU 2717 Catch That Cow

该题用广搜比较好,这里要处理好就是X*2的时候,我们知道如果一步一步地走也就最多终点与起点相减的绝对值,那么我们就不能超过终点加上他们的绝对值;

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
class Node
{
public:
int time,number;
};
Node queue[200024];
int BFS( int A, int B )
{
bool hash[200024]={0};
int dis = abs( A - B );
int first=0,end=0;
queue[end].time=0;
queue[end].number = A;
hash[A] = 1;
end++;
while( first < end )
{
Node t = queue[first];
int x = t.number + 1;
if( x <= B&&!hash[x] )
{
queue[end].number = x;
queue[end].time = t.time + 1;
hash[x] = 1;
if( x == B ) return t.time + 1;
end++;
}
x = t.number*2;
if( x <= (B + dis)&&!hash[x] )
{
queue[end].number = x;
queue[end].time = t.time + 1;
hash[x] = 1;
if( x == B ) return t.time + 1;
end++;
}
x = t.number -1;
if( x >=0 && !hash[x] )
{
queue[end].number = x;
queue[end].time = t.time + 1;
hash[x] = 1;
if( x == B ) return t.time + 1;
end++;
}
first++;
}
}
int main( )
{
int A,B;
while( scanf( "%d%d",&A,&B )==2 )
{
if( A == B ) printf( "0\n" );
else
printf( "%d\n",BFS( A , B ) );
}
return 0;
}

 

你可能感兴趣的:(catch)