• Educational Codeforces Round 16 C


    Description

    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

    题解:构造一个魔方(对角,列,行相等)

    解法:

    如3×3的魔方阵: 
        8   1   6 
        3   5   7 
        4   9   2  
    魔方阵的排列规律如下:
    (1)将1放在第一行中间一列;
    (2)从2开始直到n×n止各数依次按下列规则存放;每一个数存放的行比前一个数的行数减1,列数加1(例如上面的三阶魔方阵,5在4的上一行后一列);
    (3)如果上一个数的行数为1,则下一个数的行数为n(指最下一行);例如1在第一行,则2应放在最下一行,列数同样加1;
    (4)当上一个数的列数为n时,下一个数的列数应为1,行数减去1。例如2在第3行最后一列,则3应放在第二行第一列;
    (5)如果按上面规则确定的位置上已有数,或上一个数是第一行第n列时,则把下一个数放在上一个数的下面。例如按上面的规定,4应该放在第1行第2列,但该位置已经被占据,所以4就放在3的下面;

    #include<bits/stdc++.h>
    using namespace std;
    int a[50][50];
    int i,j,k,p,n;
    int main()
    {
        cin>>n;
        for (i=1; i<=n; i++)
        {
            for (j=1; j<=n; j++)
            {
                a[i][j]=0;
            }
        }
        p=1;
        j=n/2+1;
        a[1][j]=1;
        for (k=2; k<=n*n; k++)
        {
            i=i-1;
            j=j+1;
            if ((i<1)&&(j>n))
            {
                i=i+2;
                j=j-1;
            }
            else
            {
                if(i<1)
                {
                    i=n;
                }
                if(j>n)
                {
                    j=1;
                }
            }
            if(a[i][j]==0)
            {
                a[i][j]=k;
            }
            else
            {
                i=i+2;
                j=j-1;
                a[i][j]=k;
            }
        }
        for(i=1; i<=n; i++)
        {
            for (j=1; j<=n; j++)
            {
                if(j!=n)
                {
                    printf("%d ",a[i][j]);
                }
                else
                {
                    printf("%d",a[i][j]);
                }
            }
            printf("
    ");
        }
        return 0;
    }
    

      

  • 相关阅读:
    Linux-Oracle 安装配置步骤
    lombok 安装
    request (请求对象)
    response (响应对象)
    ServletContext (上下文对象)
    JavaWeb数据库配置
    HttpServlet
    博客园代码字体大小
    博客园背景美化
    用PHP实现反向代理服务器
  • 原文地址:https://www.cnblogs.com/yinghualuowu/p/5802044.html
Copyright © 2020-2023  润新知