zoukankan      html  css  js  c++  java
  • CodeForce 710C Magic Odd Square

    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,使n * n 的方格,行,列,主对角线相加为奇数。输出这样的正方形

    思路:
      先在第一行中间放上1,然后向右上放数,有数了就放在当前的正下方,一直到结束。

    AC代码:
     1 # include <bits/stdc++.h>
     2 using namespace std;
     3 const int MAX = 50;
     4 int a[MAX][MAX];
     5 bool vis[MAX][MAX];
     6 int main()
     7 {
     8     int n;
     9     scanf("%d", &n);
    10     memset(vis, false, sizeof(vis));
    11     a[1][n/2 + 1] = 1;
    12     int r = 1;
    13     int c = n/2 + 1;
    14     vis[r][c] = true;
    15     for(int i = 2; i <= n * n; i++)
    16     {
    17         int r1 = r;
    18         int c1 = c;
    19         r -= 1;
    20         c += 1;
    21         if(r < 1)
    22             r = n;
    23         if(c > n)
    24             c = 1;
    25         if(vis[r][c])
    26         {
    27             r = r1 + 1;
    28             c = c1;
    29         }
    30         vis[r][c] = true;
    31         a[r][c] = i;
    32         
    33     }
    34     for(int i = 1; i <= n; i++)
    35     {
    36         for(int j = 1; j <= n; j++)
    37         {
    38             if(j == 1)
    39                 cout << a[i][j];
    40             else
    41                 cout << " " << a[i][j];
    42         }
    43         cout << endl;
    44     }
    45     return 0;
    46 }
    View Code
     
    生命不息,奋斗不止,这才叫青春,青春就是拥有热情相信未来。
  • 相关阅读:
    thoughtworks家庭作业C++版本
    删除数组中等于某个key的所有元素
    一些必读的开源项目
    库函数strlen源码重现及注意问题
    判断相同树或者对称树
    约瑟夫环问题
    Loadrunner 脚本录制策略
    品味性能之道<十一>:JAVA中switch和if性能比较
    白盒静态自动化测试工具:FindBugs使用指南
    六个步骤把资料转换成知识
  • 原文地址:https://www.cnblogs.com/lyf-acm/p/5798202.html
Copyright © 2011-2022 走看看