位运算 格雷码 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

转载于:https://www.cnblogs.com/aiqin/p/4417460.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值