zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    c盘瘦身、windows解除上网限速、贴膜注意事项
    windows7导入k8s用户证书
    ubuntu报错解决和注意事项
    ubuntu默认root密码问题,第一次使用ubuntu需要设置root密码
    java程序员修炼之道
    选择器代码
    css的使用技巧资料
    移动开发的相关资料
    使用phantomjs生成网站快照
    PHP Simple HTML DOM Parser Manual-php解析DOM
  • 原文地址:https://www.cnblogs.com/yinghualuowu/p/5802044.html
Copyright © 2011-2022 走看看