C. Magic Odd Square
time limit per test:1 second
memory limit per test:256 megabytes
input:standard input
output:standard output
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
Input
The only line contains odd integer n (1 ≤ n ≤ 49).
Output
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
Examples
Input
1
Output
1
Input
3
Output
2 1 4
3 5 7
6 9 8
题目连接:http://codeforces.com/problemset/problem/710/C
题意:n*n的矩阵内填入1~n*n使得行,列,对角线的和为奇数(n为奇数)。
思路:n阶幻方(行,列,对角线的和相等)也符合这种情况。
传送门:n阶幻方
代码:
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 int x[55][55]; 5 int main() 6 { 7 int n; 8 scanf("%d",&n); 9 int i=0,j=n/2,num=1; 10 while(num<=n*n) 11 { 12 int ii=(i%n+n)%n; 13 int jj=(j%n+n)%n; 14 x[ii][jj]=num; 15 if(num%n==0) i++; 16 else --i,j++; 17 num++; 18 } 19 for(i=0;i<n;i++) 20 { 21 for(j=0;j<n;j++) 22 cout<<x[i][j]<<" "; 23 cout<<endl; 24 } 25 return 0; 26 }