码迷,mamicode.com
首页 > 其他好文 > 详细

CodeForces - 710C Magic Odd Square(奇数和幻方构造)

时间:2019-03-17 01:28:06      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:als   div   only   std   mat   codeforce   return   max   type   

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 4
3 5 7
6 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;
 } 

 

 

CodeForces - 710C Magic Odd Square(奇数和幻方构造)

标签:als   div   only   std   mat   codeforce   return   max   type   

原文地址:https://www.cnblogs.com/yzm10/p/10544981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!