Educational Codeforces Round 16 C. Magic Odd Square

本文探讨如何构造一个n×n的矩阵,该矩阵由从1到n²的不同整数组成,使得每一行、每一列及两条主对角线上的元素之和均为奇数。给出了一种简洁有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
其实这是一个很经典的问题啊,并不算简单,解决策略貌似也有很多种,这里贴几篇连接:点击打开链接 最后发现一个超级短的解决办法,但是原理不是很懂,改一改就过了
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
int f(int n, int x, int y)
{
    return (x + y*2 + 1)%n;
}

int main(int argc, char **argv)
{
    int i, j,n;
    scanf("%d",&n);
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
        {
           printf("%d ", f(n, n - j - 1, i)*n + f(n, j, i) + 1);
        }
        putchar('\n');
    }
    
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值