Magic Odd Square
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 43 5 76 9 8 题意:构造n阶幻方,填入1~n^2,使每行每列每对角线和为奇数。 思路:暴搜TLE,那么考虑构造。方法见下图,1填奇,0填偶。 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 各类幻方构造法(知乎):https://www.zhihu.com/question/30498489/answer/49208033
#include<bits/stdc++.h> #define MAX 105 using namespace std; typedef long long ll; int a[MAX][MAX],b[MAX*MAX]; int main() { int n,i,j,k; scanf("%d",&n); for(i=1;i<=n/2;i++){ j=n/2+1-i+1; for(k=1;k<=2*i-1;k++){ a[i][j+k-1]=1; } } for(i=n/2+1;i<=n;i++){ j=i-(n/2+1)+1; for(k=1;k<=n+1-(2*j-1);k++){ a[i][j+k-1]=1; } } for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ if(j>1) printf(" "); if(a[i][j]){ for(k=1;k<=n*n;k+=2){ if(b[k]) continue; b[k]=1; a[i][j]=k; break; } } else{ for(k=2;k<=n*n;k+=2){ if(b[k]) continue; b[k]=1; a[i][j]=k; break; } } printf("%d",a[i][j]); } printf("\n"); } return 0; }
原文地址:https://www.cnblogs.com/yzm10/p/10544981.html
时间: 2024-10-17 21:03:45