zoukankan      html  css  js  c++  java
  • CodeForces

    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;
     } 
     
  • 相关阅读:
    Java怎样对一个属性设置set或get方法的快捷键
    小程序怎样控制rich-text中的<img>标签自适应
    Java中Arrys数组常用的方法
    Java 怎样实现调用其他方法
    Java保留两位小数
    解决ajax请求跨域
    rand(7) 到rand(10)
    c++生成随机数
    批量该文件名
    正则表达式(=)
  • 原文地址:https://www.cnblogs.com/yzm10/p/10544981.html
Copyright © 2011-2022 走看看