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 from1 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 withn integers. All the integers should be different and from1 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
题意:给出一个奇数n,你输出一个n*n的矩阵,要求每行每列对角线和为奇数。
题解:刚开始没看到输入的是奇数,就在网上学n阶幻方,后来发现了, 我n阶幻方也快学完了,。。。。后面有大神代码,感觉不是一个世界(两个世界。。。)
代码:
#include <cstdio>//奇次幻方写法 #include <iostream> #include <cstring> #include <string> #include <cmath> #include <queue> #include <stack> #include <algorithm> #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) #define mem(a) memset(a, 0, sizeof(a)) #define eps 1e-5 #define M 100005 #define LL longlong using namespace std; int a[2510][2510]; int n,k,nn; void print() { for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { if(j!=1) printf(" %d",a[i][j]); else printf("%d",a[i][j]); } printf("\n"); } } void dfs(int x,int y) { if(k==n*n+1) return ; int fx=x-1>=1?x-1:n; int fy=y+1>n?1:y+1; if(a[fx][fy]==0) { a[fx][fy]=k++; dfs(fx,fy); } else { a[x+1][y]=k++; dfs(x+1,y); } } void solo1() { k=1; int mid=(n+1)>>1; a[1][mid]=k++; dfs(1,mid); } int main() { scanf("%d",&n); for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) a[i][j]=0; solo1(); print(); return 0; }
大神代码:
#include<bits/stdc++.h> using namespace std; int n; int main(){ cin >> n; int od = -1, ev = 0, mid = n/2 + 1; for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ if(abs(i - mid) + abs(j - mid) < mid) printf("%d ", od += 2); else printf("%d ", ev += 2); } puts(""); } return 0; }