构造题
http://www.elijahqi.win/archives/3994
Let us define a magic grid to be a square matrix of integers of size n×nn×n, satisfying the following conditions.
All integers from 00 to (n2−1)(n2−1) inclusive appear in the matrix exactly once.Bitwise XOR of all elements in a row or a column must be the same for each row and column.
You are given an integer nn which is a multiple of 44. Construct a magic grid of size n×nn×n.Input
The only line of input contains an integer nn (4≤n≤10004≤n≤1000). It is guaranteed that nn is a multiple of 44.Output
Print a magic grid, i.e. nn lines, the ii-th of which contains nn space-separated integers, representing the ii-th row of the grid.
If there are multiple answers, print any. We can show that an answer always exists.ExamplesinputCopy
4
outputCopy
8 9 1 13
3 12 7 5
0 2 4 11
6 10 15 14
inputCopy
8
outputCopy
19 55 11 39 32 36 4 52
51 7 35 31 12 48 28 20
43 23 59 15 0 8 16 44
3 47 27 63 24 40 60 56
34 38 6 54 17 53 9 37
14 50 30 22 49 5 33 29
2 10 18 46 41 21 57 13
26 42 62 58 1 45 25 61
Note
In the first example, XOR of each row and each column is 1313.
In the second example, XOR of each row and each column is 6060.
题意构造一个n*n的矩形 使得每行每列 xor之后都是相同的值
首先根据题目中给的44矩阵我们可以知道 他这个矩阵xor之后一定都是相同的值 那么可以考虑 题目中一个特定的条件 都是4的倍数 那么拆成二进制之后我们发现只要把题目中样例矩形 复制好几次就可以了 另外每次复制需要加16 因为16是一个二进制数 每次往前进位的时候 每个44的矩阵都进了相同的数 所以就能保证剩余的位数异或是0 为了更加简单我选择构造一个
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
如上的矩阵也可以满足题目中的要求 这样显然就更容易写代码了
#include<bits/stdc++.h>
using namespace std;
inline char gc(){
static char now[1<<16],*S,*T;
if (T==S){T=(S=now)+fread(now,1,1<<16,stdin);if (T==S) return EOF;}
return *S++;
}
inline int read(){
int x=0,f=1;char ch=gc();
while(!isdigit(ch)) {if (ch=='-') f=-1;ch=gc();}
while(isdigit(ch)) x=x*10+ch-'0',ch=gc();
return x*f;
}
int n;
int main(){
freopen("c.in","r",stdin);
n=read();
for (int i=0;i<n;++i){
for (int j=0;j<n;++j) printf("%d ",(i%4*4+j%4)+((i/4)*n/4+j/4)*16);
puts("");
}
return 0;
}