N的上限没有了,就老老实实地全部宽搜。有人提出用康托压缩来存储,也有道理;而这里用的仍然是上一道题的解法,只不过不再限制在10步以内而已。相比于康托压缩,我
用map来存储信息,空间消耗更大(毕竟是关联容器),时间效率也更大(人家是开放式寻址,常数时间;我顶多是二分查找,log(n)时间而已),但既然能够AC,就偷懒下
不改了。
另:貌似记忆化深搜(宽搜)+康托压缩的时间会少很多,但临考试了,就不做深究了。
Run Time: 0.23sec
Run Memory: 4528KB
Code length: 1978Bytes
SubmitTime: 2012-01-07 19:59:25
// Problem#: 1151
// Submission#: 1180308
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <cstdio>
#include <string>
#include <queue>
#include <map>
using namespace std;
void changeA( const string &s, string &t );
void changeB( const string &s, string &t );
void changeC( const string &s, string &t );
int main()
{
int M;
string now, target;
int i, j;
map<string, string> m;
target = "12348765";
m[ target ].clear();
queue<string> q;
q.push( target );
while ( !q.empty() ) {
now = q.front();
changeA( now, target );
if ( m.find( target ) == m.end() ) {
m[ target ] = m[ now ] + 'A';
q.push( target );
}
changeB( now, target );
if ( m.find( target ) == m.end() ) {
m[ target ] = m[ now ] + 'B';
q.push( target );
}
changeC( now, target );
if ( m.find( target ) == m.end() ) {
m[ target ] = m[ now ] + 'C';
q.push( target );
}
q.pop();
}
while ( scanf( "%d", &M ) && M != -1 ) {
for ( i = 0; i < 8; i++ ) {
scanf( "%d", &j );
target[ i ] = '0' + j;
}
if ( m.find( target ) == m.end() || m[ target ].size() > M )
printf( "-1\n" );
else
printf( "%d %s\n", m[ target ].size(), m[ target ].c_str() );
}
return 0;
}
void changeA( const string &s, string &t ) {
t[ 0 ] = s[ 4 ];
t[ 1 ] = s[ 5 ];
t[ 2 ] = s[ 6 ];
t[ 3 ] = s[ 7 ];
t[ 4 ] = s[ 0 ];
t[ 5 ] = s[ 1 ];
t[ 6 ] = s[ 2 ];
t[ 7 ] = s[ 3 ];
}
void changeB( const string &s, string &t ) {
t[ 0 ] = s[ 3 ];
t[ 1 ] = s[ 0 ];
t[ 2 ] = s[ 1 ];
t[ 3 ] = s[ 2 ];
t[ 4 ] = s[ 7 ];
t[ 5 ] = s[ 4 ];
t[ 6 ] = s[ 5 ];
t[ 7 ] = s[ 6 ];
}
void changeC( const string &s, string &t ) {
t[ 0 ] = s[ 0 ];
t[ 1 ] = s[ 5 ];
t[ 2 ] = s[ 1 ];
t[ 3 ] = s[ 3 ];
t[ 4 ] = s[ 4 ];
t[ 5 ] = s[ 6 ];
t[ 6 ] = s[ 2 ];
t[ 7 ] = s[ 7 ];
}