您的位置:首页 > 其它

codeforces 710C C. Magic Odd Square(构造)

2016-08-23 22:55 417 查看
题目链接:

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.

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

题意:

找出一个n*n的矩阵,这里面的数是一个[1,n*n]的全排列,要求所有行所有列的和为奇数;n为奇数;

思路:

可以发现n为奇数的时候就是每行每列的个数都是奇数,所有每行每列里面的奇数的个数都是奇数,所有就可以想到中间是一个奇数组成的45度的正方形,其他是偶数;正好用完了所有的偶数和奇数;

AC代码:


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <bits/stdc++.h>
#include <stack>
#include <map>

using namespace std;

#define For(i,j,n) for(int i=j;i<=n;i++)
#define mst(ss,b) memset(ss,b,sizeof(ss));

typedef  long long LL;

template<class T> void read(T&num) {
char CH; bool F=false;
for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar());
for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar());
F && (num=-num);
}
int stk[70], tp;
template<class T> inline void print(T p) {
if(!p) { puts("0"); return; }
while(p) stk[++ tp] = p%10, p/=10;
while(tp) putchar(stk[tp--] + '0');
putchar('\n');
}

const LL mod=1e9+7;
const double PI=acos(-1.0);
const int inf=1e9;
const int N=3e5+10;
const int maxn=1e3+20;
const double eps=1e-12;

int ans[50][50];

int main()
{

int n;
read(n);

int cnt1=1,cnt2=2,cx=n/2+1,cy=n/2+1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(abs(cx-i)+abs(cy-j)<=n/2)ans[i][j]=cnt1,cnt1+=2;
else ans[i][j]=cnt2,cnt2+=2;
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<n;j++)printf("%d ",ans[i][j]);
printf("%d\n",ans[i]
);
}

return 0;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: