zoukankan      html  css  js  c++  java
  • codeforces 710C Magic Odd Square(构造或者n阶幻方)

    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
    分析:给你与1个奇数n, 让你构造一个n * n 的矩阵,要求保证这个矩阵的每行每列和主对角线上数字的和为奇数。
    构造:
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 int ans[50][50];
     4 
     5 int main()
     6 {
     7     int n;
     8     ios::sync_with_stdio(false);
     9     cin.tie(0);
    10     cin >> n;
    11     memset(ans,0,sizeof(ans));
    12     int num1 = 1,num2 =2,cnt1 = (n+1)/2,cnt2 = (n+1)/2;
    13     for(int i = 1; i <= n; i++)
    14     {
    15         for(int j = 1; j <= n; j++)
    16         {
    17             if(abs(cnt1 - i) + abs(cnt2 - j) <= n/2) // 为什么这么写,有点不清楚
    18                 ans[i][j] = num1,num1 += 2;
    19             else
    20                 ans[i][j] = num2,num2 += 2;
    21         }
    22     }
    23     for(int i = 1; i <= n; i++)
    24     {
    25         for(int j = 1; j< n; j++)
    26         {
    27             printf("%d ",ans[i][j]);
    28         }
    29         printf("%d
    ",ans[i][n]);
    30     }
    31     return 0;
    32 }

    n阶幻方:

     1 # include <stdio.h>  
     2 # include <string.h>  
     3 int g[50][50];  
     4 int main(){  
     5     int i, j, k, n, x, y, r, c;  
     6     memset(g, 0, sizeof(g));  
     7     scanf("%d", &n);  
     8     r=1; c=(1+n)/2;  
     9     g[1][c]=1;  
    10       
    11     for(i=2; i<=n*n; i++){  
    12         x=r;y=c;  
    13         x=x-1;  
    14         if(x<1){  
    15             x=n;  
    16         }  
    17         y=y+1;  
    18         if(y>n){  
    19             y=1;  
    20         }  
    21         if(g[x][y]){  
    22             g[r+1][c]=i;  
    23             r=r+1;  
    24         }  
    25         else{  
    26             g[x][y]=i;  
    27             r=x;c=y;  
    28         }  
    29     }  
    30     for(i=1; i<=n; i++){  
    31         for(j=1; j<=n; j++){  
    32             if(j!=n)  
    33             printf("%d ", g[i][j]);  
    34             else{  
    35                 printf("%d
    ", g[i][j]);  
    36             }  
    37         }  
    38           
    39     }  
    40     return 0;  
    41 }  
  • 相关阅读:
    PE系统盘
    python常用方法手记
    python tushare
    idea导入导出java jar包
    javaweb项目配置tomcat启动
    window安装tomcat
    解决idea控制台乱码
    maven手记
    java redis常见问题
    java mysql常见问题
  • 原文地址:https://www.cnblogs.com/PrayG/p/5809979.html
Copyright © 2011-2022 走看看