Sicily|1721. Gray code[Special judge]



Time Limit: 1sec    Memory Limit:32MB
Description
Gray code is an interesting code sequence and has many applications in computer science.  
No matter you have known it before or not, here are some introductions about its features:
(1)Gray code has 2 unique elements;
(2)Each element contains n digits of 0 or 1;
(3)Each pair of adjacent elements has exactly one different digit.
For example, when n=2, one of the gray code sequences is: 00,01,11,10.  Now, the task is quite
simple, given a positive integer n, generate the corresponding Gray code sequence.
Input
Input may contain multiple test cases. Each test case consists of one positive integer n(n<=16), 
input is terminated by a case with n=0, which should not be processed.
Output
For each test case, output the corresponding Gray code sequence, one element per line. There 
may be multiple answers, any of them will be accepted. Please output a blank line after each test case.
Sample Input
 Copy sample input to clipboard
1
2
0
Sample Output
0
1

00
01
11
10

思路: 

题目只要求满足格雷码的一组解,所以可以通过递推构造一组解。观察下面的例子:
-       后两位补0: 
0      000
1      100  
--      后一位补0: 
11     110
01     010
---     不补0:
011   011
111  111
101   101
001   001

可以发现明显的对称性,根据bit位数的不同,通过把之前的结果倒叙并在最后一位补个'1'就可。
还可以参考另外一篇的介绍 格雷码介绍
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int n;
const int MAXN = 16;

char a[1<<MAXN][MAXN+1]; // 一行代表一个数字, 代表1~2^n 这些数字 
void copyAndAdd1(char* s, char* e, char*d){
	while(s != e){
		*d++ = *s++;
	} *d = '1';
}
int main(){
	while(scanf("%d", &n) != EOF){
		if(n == 0) return 0;
		memset(a, '0', sizeof(a));
		a[0][0] = '1';
		int num = 2;
		for(int i = 2; i <= n; i++){
			int copyBitsNum = i-1;
			int s = num;
			num <<= 1;
			for(int j = 0, e = num-1; j < s; j++, e--){
				copyAndAdd1(a[j], a[j]+copyBitsNum, a[e]);
			}
		}
		for(int i = 0; i < num; i++){
			a[i][n] = '\0';
			printf("%s\n", a[i]);
		} printf("\n");
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值