sgu 249 Matrix

249. Matrix

time limit per test: 1 sec.
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

Author: Antony Popovich
Resource: Petrozavodsk Summer Training Sessions 2004
Date: August 25, 2004





//gray 码 解法 看Matrix 67 大神的位运算
http://www.matrix67.com/blog/archives/266

关于 n的 gray码 n^(n>>1)
我的理解是 两个不同的数x,y的 x^(x>>1) 和 y^(y>>1) 相差第一位
那么 x^y =1...1 (n个1)
首先 说下 x^(x>>1) 和 y^(y>>1) 去掉第一位相等 那么 有 x1^x2=y1^y2 这样 我们进行讨论(xi是x二进制表示的第i位 是从左往右数的 )
1. x1^x2=0 那么 x1=x1 y1=y2 所以y1,y2要么等于 x1,x2,要么是 ~x1,~x2;
2. x1^x2=1 那么 x1!=x2 y1!=y2
a: x1=1 x2=0 那么 1: y1=1,y2=0 2: y1=0,y2=1
b: x1=0,x2=1 ....同理

分析如果y1=x1 那么 y2=x2 ... yi=xi; 这样就 x=y,与最早说的 两个不同的数x,y 矛盾
如果y1!=x1 那么 y2!=x2 ...yi!=xi 这样 x,y各位都不等 那就是 相加为 1..1 (n个1)
所以: 两个不同的数x,y的 x^(x>>1) 和 y^(y>>1) 相差第一位
那么 x^y =1...1 (n个1) 而这样的 x,y是对称的 ,可以去看 matrix 67 大神的博客
#include <iostream> #include <stdio.h> #include <math.h> #include <string.h> #include <algorithm> using namespace std; int main() { int i,j,n,m; while(scanf("%d %d",&n,&m)!=EOF) { for(i=0;i<(1<<n);printf("\n"),i++) { j=0; printf("%d",((j^(j>>1))<<n)^(i^(i>>1))); for(j=1;j<(1<<m);j++) printf(" %d",((j^(j>>1))<<n)^(i^(i>>1))); } } return 0; }
原文地址:https://www.cnblogs.com/372465774y/p/2738568.html