Codeforces 710C. Magic Odd Square n阶幻方

本文介绍如何构造一个n*n的矩阵,该矩阵中包含从1到n*n的不同整数,使得每一行、每一列及两个主对角线上的数字之和均为奇数。通过特定算法生成矩阵,并附带实现代码。
C. Magic Odd Square
time limit per test:1 second
memory limit per test:256 megabytes
input:standard input
output:standard output

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
题目连接:http://codeforces.com/problemset/problem/710/C

题意:n*n的矩阵内填入1~n*n使得行,列,对角线的和为奇数(n为奇数)。
思路:n阶幻方(行,列,对角线的和相等)也符合这种情况。
传送门:n阶幻方
代码:
 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 int x[55][55];
 5 int main()
 6 {
 7     int n;
 8     scanf("%d",&n);
 9     int i=0,j=n/2,num=1;
10     while(num<=n*n)
11     {
12         int ii=(i%n+n)%n;
13         int jj=(j%n+n)%n;
14         x[ii][jj]=num;
15         if(num%n==0) i++;
16         else --i,j++;
17         num++;
18     }
19     for(i=0;i<n;i++)
20     {
21         for(j=0;j<n;j++)
22             cout<<x[i][j]<<" ";
23         cout<<endl;
24     }
25     return 0;
26 }
n为奇数
 
 

转载于:https://www.cnblogs.com/GeekZRF/p/5869962.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值