您的位置:首页 > 其它

Sicily|1721. Gray code[Special judge]

2016-05-18 09:03 387 查看
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 2n 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]
= '\0';
printf("%s\n", a[i]);
} printf("\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: