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
其实这是一个很经典的问题啊,并不算简单,解决策略貌似也有很多种,这里贴几篇连接:点击打开链接 最后发现一个超级短的解决办法,但是原理不是很懂,改一改就过了
#include <stdio.h> #include <stdlib.h> #include <cstdio> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j,n; scanf("%d",&n); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%d ", f(n, n - j - 1, i)*n + f(n, j, i) + 1); } putchar('\n'); } return 0; }