sgu 249 Matrix
2009-01-30 17:31
309 查看
249. Matrix
time limit per test: 2sec.
memory limit per test: 65536
KB
input: standard
output: standard
It
is necessary to arrange numbers from 0 to 2^(N+M)-1 in the matrix with
2^N rows and 2^M columns. Moreover, numbers occupying two adjacent
cells must differ only in single bit in binary notation. Cells are
adjacent if they have common side. Matrix is cyclic, i.e. for each row
the leftmost and rightmost matrix cells are considered to be adjacent
(the topmost and the bottommost matrix cells are also adjacent).
Input
The first line of input contains two integers N and M (0<N,M; N+M<=20).
Output
Output file must contain the required matrix in a form of 2^N lines of 2^M integers each.
Sample test(s)
Input
1 1
Output
0 2
1 3
这道题目要求一个矩阵,使得每个元素和其相邻的元素在二进制表示上相差1位,且每行(每列)开头和每行结尾也二进制表示也相差1位。
考虑二进制的Gary编码,Gary吗为这样一种编码,其元素个数为2的整数幂,且每个相邻的元素在二进制表示上相差1位。
如2个元素的Gary码为:
0
1
2^n个元素的Gary码可以由2^n-1个元素的Gary 码来构成,具体方法如下,将2^n-1个元素的Gary码镜像对称的写在原来的2^n-1个Gary码下面。然后在前2^n-1个Gary 码前面添0, 在后2^n-1个Gary码前面添1
则构成2^n个元素的Gary码,如:
0 0 00
1 1 01
---》 1 ---》 11
0 10
给出一种简单的构造n位Gary码的方法 ,观察可知,第 ith Gary 码可以表示为 i^(i>>1)
则构造n位Gary码的代码为 MaxN=2^n, int data[MaxN]:
for(i=0;i<MaxN;++i) data[i]=i^(i>>1);
那么这道题目可以构造求解,对第一列,构造N位的Gary吗,对第一一行构造M位的Gary码,对第一行的每一个元素,将其左移N位。然后d[i][j]=d[i][0]+d[0][j];(1<=i<2^N,1<=j<2^M)
题目的全部代码如下:
#include "cstdio" #include "cstdlib" int N,M; int MaxN,MaxM; int **data; void output(); void init(){ int i; i=0; MaxN=MaxM=1; while(i++<N) MaxN<<=1; i=0; while(i++<M) MaxM<<=1; data=(int**)malloc(MaxN*sizeof(int*)); for(i=0;i<MaxN;++i) data[i]=(int*)malloc(MaxM*sizeof(int)); } int POW(int n){ int ans=1; int i=0; while(i++<n) ans<<=1; return ans; } void work(){ int i,j,k; for(i=0;i<MaxN;++i) data[i][0]=i^(i>>1); for(i=1;i<MaxM;++i) data[0][i]=((i^(i>>1))<<N); for(i=1;i<MaxN;++i) for(j=1;j<MaxM;++j) data[i][j]=data[0][j]+data[i][0]; } void output(){ int i,j,k; for(i=0;i<MaxN;++i){ for(j=0;j<MaxM;++j) printf("%d ",data[i][j]); putchar('/n'); } } int main(){ scanf("%d%d",&N,&M); init(); work(); output(); return 0; }
相关文章推荐
- sgu-249 Matrix
- sgu 249 Matrix
- SGU 249 Matrix
- SGU 168 Matrix (DP)
- SGU - 168 Matrix 简单递推
- sgu 168 Matrix
- SGU127-Telephone directory
- SGU117—Counting (快速幂取模)
- Android Matrix理论与应用详解
- sgu 165 Basketball 贪心构造
- sgu 199 Beautiful People dp
- SGU131 - Hardwood floor(状态压缩DP)
- .net chart 控件“Not initialize 3D Matrix(未初始化三维矩阵)”问题
- SGU 177 Square(并查集)
- Android Matrix理论与应用详解
- Search a 2D Matrix
- LeetCode Spiral Matrix II 带打印程序
- POJ 3422 Kaka's Matrix Travels 最小费用流
- Spiral Matrix
- CodeForces 375 B. Maximum Submatrix 2