【NOIP2015】【Luogu2615】神奇的幻方(模拟填数)

problem

  • 给一定n*n的矩阵,要求填上1~n*n的数,使之每行、列、对角线的和都相等。
  • n为奇数时,按如下步骤构建:
    1.若(K−1)在第一行但不在最后一列,则将K填在最后一行,(K−1)所在列的右一列;
    2.若(K−1)在最后一列但不在第一行,则将K填在第一列,(K−1)所在行的上一行;
    3.若(K−1)在第一行最后一列,则将K填在(K−1)的正下方;
    4.若(K−1)既不在第一行,也不在最后一列,如果(K−1)的右上方还未填数,则将K填在(K−1)的右上方,否则将K填在(K−1)的正下方。
  • 输入奇数n<39,输出幻方。

solution

直接模拟,填数

codes

#include<iostream>
#include<cstring>
using namespace std;

const int maxn = 50;
int a[maxn][maxn];

int main(){
    memset(a,0,sizeof(a));//数组清零
    int n;  cin>>n;
    int x = 1, y = (n+1)/2, tot = n*n;//中间位置
    a[x][y] = 1;
    for(int k = 2; k <= tot; k++){
        if(x==1 && y!=n){
            a[n][y+1] = k;//注意k++
            x = n, y = y+1;
            continue;//x,y值改变了要continue
        }
        if(x!=1 && y==n){//条件看错
            a[x-1][1] = k;
            x = x-1, y = 1;
            continue;
        }
        if(x==1 && y==n){
            a[x+1][y] = k;
            x = x+1, y = y;
            continue;
        }
        if(x!=1 && y!=n){
            if(a[x-1][y+1]==0){
                a[x-1][y+1] = k;
                x = x-1, y = y+1;
            }else{
                a[x+1][y] = k;
                x = x+1, y = y;
            }
            continue;
        }
    }
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){
            cout<<a[i][j]<<" ";
        }
        cout<<'\n';
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_33957603/article/details/82837965