位运算 格雷码 gray

题目:

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
解答:
#include<cstdio>
#include<iostream>
#include<iomanip>
using namespace std;
 
int main(){
 
 int x,y,m,n,u;
 cin>>m>>n;
 cout<<(1<<m)<<" "<<(1<<n)<<endl;
 for(x = 0;x <= (1<<m) - 1;x++){
  u = (x ^ (x >> 1))<<n;//前m位
  for(y = 0;y <= (1<<n) - 1;y++){
   cout<<setw(3)<<(u | (y ^ (y >> 1)))<<" ";//前m位与后面的n位合起来
  }
  cout<<endl;
 }
 
 return 0;
}

参见:

http://www.matrix67.com/blog/archives/266

posted @ 2015-04-11 12:43  Qin&Yang  阅读(359)  评论(0编辑  收藏  举报