/*
zoj_2416 搜索
简单bfs
不标记必然MLE,记得标记就好
*/
#include <iostream>
#include <cstdio>
#include <queue>
#include <string.h>
using namespace std;
bool flag[10000];
struct node
{
int num[4];
int step;
node( int n=0,int s=0 )
{
int i;
i=3;
while( n!=0 )
{
num[i]=n%10;
n/=10;
i--;
}
step=s;
}
};
int add( int a )
{
if( a==9 ) return 1;
else return a+1;
}
int minu( int a )
{
if( a==1 ) return 9;
else return a-1;
}
bool equal( node a,node b )
{
int i;
for( i=0;i<4;i++ )
if( a.num[i]!=b.num[i] )
break;
if( i==4 ) return true;
else return false;
}
int main()
{
int T,a,b,s,i,num;
node temp,temp1;
queue <node>q;
scanf( "%d",&T );
while( T-- )
{
memset( flag,0,sizeof(flag) );
scanf( "%d%d",&a,&b );
node bb(b);
q.push( node(a,0) );
while( !q.empty() )
{
temp=q.front(); q.pop();
if( equal( temp,bb ) ) break;
for( i=0;i<4;i++ )
{
temp1=temp;
temp1.num[i]=add( temp1.num[i] );
temp1.step++;
num=1000*temp1.num[0]+100*temp1.num[1]+10*temp1.num[2]+temp1.num[3];
if( !flag[num] )
flag[num]=1 , q.push( temp1 );
}
for( i=0;i<4;i++ )
{
temp1=temp;
temp1.num[i]=minu( temp1.num[i] );
temp1.step++;
num=1000*temp1.num[0]+100*temp1.num[1]+10*temp1.num[2]+temp1.num[3];
if( !flag[num] )
flag[num]=1 , q.push( temp1 );
}
for( i=0;i<3;i++ )
{
temp1=temp;
swap( temp1.num[i],temp1.num[i+1] );
temp1.step++;
num=1000*temp1.num[0]+100*temp1.num[1]+10*temp1.num[2]+temp1.num[3];
if( !flag[num] )
flag[num]=1 , q.push( temp1 );
}
}
printf( "%d\n",temp.step );
while( !q.empty() ) q.pop();
}
return 0;
}
zoj 2416
最新推荐文章于 2016-08-11 07:25:28 发布