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

Posted yzm10

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CodeForces - 710C Magic Odd Square(奇数和幻方构造)相关的知识,希望对你有一定的参考价值。

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("
");
    }
    return 0;
 } 

 

 

以上是关于CodeForces - 710C Magic Odd Square(奇数和幻方构造)的主要内容,如果未能解决你的问题,请参考以下文章

codeforces 710C Magic Odd Square(构造或者n阶幻方)

Vasya and Magic Matrix CodeForces - 1042E (概率dp)

?????????????????????Codeforces Educational Codeforces Round 9 Magic Matrix

Codeforces 670D. Magic Powder

Magic Powder - 1 CodeForces - 670D1

CodeForces 670D Magic Powder