本文主要是介绍Educational Codeforces Round 16 C. 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.
The only line contains odd integer n (1 ≤ n ≤ 49).
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.
1
1
3
2 1 4 3 5 7 6 9 8
给你一个奇数,让你构造一个n*n的矩阵,矩阵的每一行,每一列还有对角线上数字的和都是奇数。
因为和是奇数,所以每一行每一列还有对角线上的数字的奇数肯定是奇数个。我们用1表示奇数,2表示偶数画出两个矩阵来看一下
n=3时
2 1 2
1 1 1
2 1 2
n=5时
2 2 1 2 2
2 1 1 1 2
1 1 1 1 1
2 1 1 1 2
2 2 1 2 2
可以发现到矩阵中心曼哈顿距离小于等于n/2的都是奇数,其他的都是偶数。(其实我是看别人的)
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>using namespace std;int main(void)
{int n,i,j,x;while(scanf("%d",&n)==1){int odd = 1,even = 2;int m = n/2 + 1;for(i=1;i<=n;i++){for(j=1;j<=n;j++){if(abs(i - m) + abs(j - m) <= n/2){x = odd;odd+=2;}else{x = even;even+=2;}printf("%d ",x);}printf("\n");}}
}
这篇关于Educational Codeforces Round 16 C. Magic Odd Square的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!