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"); } }
相关文章推荐
- Spring MVC之@RequestBody, @ResponseBody 详解
- 基于OK6410的WIFI四驱小车(下)
- iOS模块化之路(一)
- android 属性动画
- 实现FTP的文件上传与下载
- 根据刚学的网络知识画的简单的图
- NYOJ 58 最少步数(dfs)
- maven关于jstl
- Android发送短信解决字数限制问题
- JQuery 的跨域方法推荐_可跨任何网站
- exchange online eDiscovery PST Export Tool运行报错处理
- <jsp:forward >标签
- hdu 1878
- Java NIO框架Netty教程(四) – ServerBootStrap启动流程源码分析
- Java参数传值还是传引用
- git之https或http方式设置记住用户名和密码的方法
- MVC3.0 中Razor 学习
- 信道信息的获取和应用
- Java NIO框架Netty教程(三) – Object对象传递
- 模拟实现通讯录-文件的方法