格雷码的第n位等于对应的二进制码的第n-1位和第n位的异或,而最左边的第1位是相同的。这道题最好用printf以%s进行输出,可以节约不少时间。而至于题目是Special Judge,以其他形式进行排列是否可以得到更好的结果就不得而知了。
Run Time: 0.04sec
Run Memory: 288KB
Code Length: 731Bytes
Submit Time: 2013-02-28 22:06:32// Problem#: 1721
// Submission#: 1928852
// 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 <cstring>
#include <cmath>
using namespace std;
int main()
{
int n;
char code[ 16 ], gray[ 17 ];
int i, j;
while ( scanf( "%d", &n ) && n ) {
memset( code, '0', sizeof( code ) );
gray[ n ] = '\0';
for ( i = powl( 2, n ); i > 0; i-- ) {
gray[ 0 ] = code[ 0 ];
for ( j = 1; j < n; j++ )
gray[ j ] = ( code[ j - 1 ] == code[ j ] ? '0': '1' );
printf( "%s\n", gray );
for ( j = n - 1; j >= 0; j-- ) {
code[ j ] = ( code[ j ] == '1' ? '0': '1' );
if ( code[ j ] == '1' )
break;
}
}
printf( "\n" );
}
return 0;
}