[Educational Codeforces Round 16]C. Magic Odd Square

[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.

输入示例


输出示例


数据规模及约定

见“输入

题解

构造幻方即可。上网搜一下 NOIP2015 Day T1.

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <cstring>
#include <string>
#include <map>
#include <set>
using namespace std; const int BufferSize = 1 << 16;
char buffer[BufferSize], *Head, *Tail;
inline char Getchar() {
if(Head == Tail) {
int l = fread(buffer, 1, BufferSize, stdin);
Tail = (Head = buffer) + l;
}
return *Head++;
}
int read() {
int x = 0, f = 1; char c = getchar();
while(!isdigit(c)){ if(c == '-') f = -1; c = getchar(); }
while(isdigit(c)){ x = x * 10 + c - '0'; c = getchar(); }
return x * f;
} #define maxn 55
int n, A[maxn][maxn]; int main() {
n = read(); int x = 1, y = (n >> 1) + 1, tot = 0;
A[x][y] = ++tot;
while(tot < n * n) {
if(x == 1 && y != n){ x = n; y++; A[x][y] = ++tot; continue; }
if(x != 1 && y == n){ x--; y = 1; A[x][y] = ++tot; continue; }
if(x == 1 && y == n){ x++; A[x][y] = ++tot; continue; }
if(x != 1 && y != n) {
if(!A[x-1][y+1]){ x--; y++; A[x][y] = ++tot; continue; }
x++; A[x][y] = ++tot;
}
} for(int i = 1; i <= n; i++) {
for(int j = 1; j < n; j++) printf("%d ", A[i][j]);
printf("%d\n", A[i][n]);
} return 0;
}
上一篇:Educational Codeforces Round 24 A 水 B stl C 暴力 D stl模拟 E 二分


下一篇:JavaScript实现TwoQueues缓存模型