HDU 1195 Open the Lock

刚开始用暴搜一直RE了,后来加了一个标记就是把字符串转化成数字,如果出现过就标记它;有一组测试数据就是1111与5555是16;

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
class Node
{
public:
int step;
char c[6];
Node() { memset( c , 0, sizeof( c ) ); }
};
char num1[6],num2[6];
Node queue[10024];
bool hash[10000];
bool push_queue( int step , int &end , char s[],Node queue[] )
{
queue[end].step = step;
strcpy(queue[end].c , s);
if( strcmp( queue[end].c , num2 )==0 ) return true;
end++;
return false;
}
int getnum( char s[] )
{
return (s[0]-'0')*1000 + (s[1]-'0')*100+(s[2]-'0')*10+(s[3]-'0');
}
int BFS( )
{

int first = 0 ,end = 0;
char s[6];
Node t;
strcpy( t.c , num1 );
t.step = 0;
queue[end] = t;
end++;
hash[getnum( num1 )]=1;
while( first < end )
{
t = queue[first];
// printf( "%s\n",t.c );
// getchar();
for( int i= 0 ; i < 4 ; i++ )
{
if( i<3 )
{
strcpy( s , t.c );
char str = s[i];
s[i]=s[i+1];
s[i+1]=str;
int number = getnum(s);
if( !hash[number] )
if(push_queue( t.step + 1 , end ,s, queue ))
return t.step + 1;
hash[number] = 1;
}
if( t.c[i]=='9' )
{
strcpy( s , t.c );
s[i] -= 1;
int number = getnum(s);
if( !hash[number] )
if(push_queue( t.step + 1 , end ,s, queue ))
return t.step + 1;
hash[number] =1;
strcpy( s , t.c );
s[i] = '1';
number = getnum(s);
if( !hash[number] )
if( push_queue( t.step + 1 , end ,s, queue ))
return t.step + 1;
hash[number] = 1;
}
else
{
if( t.c[i]=='1' )
{
strcpy( s , t.c );
s[i] += 1;
int number = getnum(s);
if( !hash[number] )
if(push_queue( t.step + 1 , end ,s, queue ))
return t.step + 1;
hash[number] = 1;
strcpy( s , t.c );
s[i] = '9';
number = getnum(s);
if( !hash[number] )
if( push_queue( t.step + 1 , end ,s, queue ))
return t.step + 1;
hash[number]=1;
}
else
{
strcpy( s , t.c );
s[i] += 1;
int number = getnum(s);
if( !hash[number] )
if(push_queue( t.step + 1 , end ,s, queue ))
return t.step + 1;
hash[number] = 1;
strcpy( s , t.c );
s[i] -=1 ;
number = getnum(s);
if( !hash[number] )
if( push_queue( t.step + 1 , end ,s, queue ))
return t.step + 1;
hash[number]=1;
}
}
}
first++;
}
return 0;
}
int main( )
{
int n;
while( scanf( "%d",&n )==1 )
{
while( n-- )
{
memset( hash , 0 ,sizeof( hash ) );
scanf( "%s%s",num1,num2 );
if( strcmp( num1 , num2 )==0 ) printf( "0\n" );
else
printf( "%d\n", BFS( ) );
}
}
return 0;
}

 

你可能感兴趣的:(Lock)