When we see the sensitive geek words, we read this question first, and then calculate various la s on the paper...
Question: Construct an anti-Magic Square (which seems to be the opposite of the Magic Square ). It is actually a simple search rule,
My constructor: When the value is greater than or equal to the 5th order, place 1 to n * n in the left-to-right and top-to-bottom order.
This section discusses the order parity of the magic square.
Odd Number: the row and, column and, diagonal and are all N times of the corresponding intermediate number, satisfying a * n (A is a positive integer) therefore, only the four columns and rows in the middle are equal to each other in the diagonal corner. You only need to replace the corresponding numbers so that they are not in the form of a * n and are not equal to each other, because the order is greater than or equal to 5, you can find the corresponding exchange so that the corresponding and become a * n + 1, A * n + 2, A * N-1, A * N-2 (level 3 may have a * N1-2 that is equal to a * N2 + 1 ).
Even number: the row, column, and column must meet 4 * n + 2. At this time, there are only two diagonal signs and can be equal, when the order is greater than 4, you can simply replace the four numbers in the middle with two, construct two 4 * n numbers (in order 4, two 4 * n numbers are equal ).
The sample can be output directly for levels 3 and 4.
There are many constructor methods, and it seems satisfying to find any formula on the Internet for the snake-like arrangement. A simple constructor is to randomly generate a matrix and then perform various search transformations until the conditions are met.
The code is slightly bypassed and output directly.
#include <cstdio>#include <string.h>int ans[205][205];int I=0;void swap (int &a,int &b){ a^=b^=a^=b;}int main (){ int n,i,j; int cas; scanf("%d",&cas); while (cas--) { scanf("%d",&n); int t=0; for (i=0 ; i<n ; ++i) for (j=0 ; j<n ; ++j) { ans[i][j]=++t; } if(n==3) { ans[0][0]=7;ans[0][1]=5;ans[0][2]=2; ans[1][0]=1;ans[1][1]=4;ans[1][2]=8; ans[2][0]=3;ans[2][1]=6;ans[2][2]=9; } else if(n==4) { ans[0][0]=2;ans[0][1]=8;ans[0][2]=15;ans[0][3]=1; ans[1][0]=5;ans[1][1]=12;ans[1][2]=10;ans[1][3]=16; ans[2][0]=6;ans[2][1]=9;ans[2][2]=4;ans[2][3]=14; ans[3][0]=3;ans[3][1]=7;ans[3][2]=11;ans[3][3]=13; } else if(n&1) { swap(ans[n/2][n/2],ans[n/2][n/2+1]); swap(ans[n/2-1][n/2+1],ans[n/2-1][n/2-1]); } else { swap(ans[n/2-1][n/2-1],ans[n/2-1][n/2]); } printf("Case #%d:\n",++I); for (i=0 ; i<n ; ++i) { int sum=0; for (j=0 ; j<n ; ++j) { printf("%d ",ans[i][j]); } printf("\n"); } } return 0;}