题目链接:http://codeforces.com/problemset/problem/710/C
C. Magic Odd Square
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
Copy
1
Output
1
Input
Copy
3
Output
2 1 4 3 5 7 6 9 8
题意:
给出1个n*n的矩阵,保证n是odd,把1-n^2每个数都必须用1次填在矩形中,保证每行每列,2条对角线和都为odd.
题解:
简单的构造,若为奇数,则一行的n个数中必须有奇数个偶数,可以构造一个中心正方形,其他全填偶数。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define x0 x0___
#define y0 y0___
#define pb push_back
#define SZ(X) ((int)X.size())
#define mp make_pair
#define fi first
#define se second
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pli pair<ll,int>
#define pil pair<int,ll>
#define ALL(X) X.begin(),X.end()
#define RALL(X) X.rbegin(),X.rend()
#define rep(i,j,k) for(int i = j;i <= k;i ++)
#define per(i,j,k) for(int i = j;i >= k;i --)
#define mem(a,p) memset(a,p,sizeof(a))
#define fastio std::ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
const ll MOD = 1E9 + 7;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
ll qmod(ll a,ll b,ll c) {ll res=1;a%=c; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%c;a=a*a%c;}return res;}
template<typename T, typename S>
void upmax(T& a,S b){if(a<b) a=b;}
template<typename T, typename S>
void upmin(T& a,S b){if(a>b) a=b;}
template<typename T>
void W(T b){cout << b << endl;}
void gettle() {while(1);}
void getre() {int t=0;t/=t;}
/
/
/
/
const int N = 55;
int ans[N][N];
set<int>odd,even;
int n;
int f(int i)
{
if(i > n / 2 + 1) i = n + 1 - i;
return i;
}
int main()
{
scanf("%d", &n);
rep (i,1,n*n) {
if(i&1) odd.insert(i);
else even.insert(i);
}
rep (i,1,n) {
rep (j,1,n/2+1) {
int rj = n + 1 - j;
if( rj - j + 1 <= 2 * f(i) - 1 ) {
ans[i][j] = *odd.begin();
odd.erase(odd.begin());
if(j == rj) continue;
ans[i][rj] = *odd.begin();
odd.erase(odd.begin());
}
}
rep (j,1,n) {
if(!ans[i][j]) {
ans[i][j] = *even.begin();
even.erase(even.begin());
}
}
}
assert(even.empty());
assert(odd.empty());
rep(i,1,n) rep(j,1,n) printf("%d%c",ans[i][j],j==n?'\n':' ');
return 0;
}