Educational Codeforces Round 16-C. Magic Odd Square

来源:互联网 发布:图片不停绕中心旋转js 编辑:程序博客网 时间:2024/05/29 13:25

原题链接

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 43 5 76 9 8

把中间一行全变成奇数,中间一列为奇数,然后遍历整个矩阵,若d[i][j] == 0 && d[i+1][j] == 0 && d[i][j+1] == 0 && d[i+1][j+1] == 0, 全为奇数,直到奇数用尽,剩下的为偶数

#include <bits/stdc++.h>#define maxn 100005#define MOD 1000000007typedef long long ll;using namespace std;int d[50][50];int main() {int n;scanf("%d", &n); int odd = -1, even = 0;for(int i = 0; i < n; i++){  d[n/2][i] = odd += 2;  if(n/2 == i)   continue;  d[i][n/2] = odd += 2;}for(int i = 0; i < n-1; i++){int sign = 0; for(int j = 0; j < n-1; j++) { if(d[i][j] == 0 && d[i+1][j] == 0 && d[i][j+1] == 0 && d[i+1][j+1] == 0) { if(odd == n * n) { sign = 1; break; } d[i][j] = odd += 2; d[i+1][j] = odd += 2; d[i][j+1] = odd += 2; d[i+1][j+1] = odd += 2; } } if(sign)  break;}for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) { if(d[i][j] == 0)  d[i][j] = even += 2; } for(int i = 0; i < n; i++){  for(int j = 0; j < n; j++) {  if(j == 0)   printf("%d", d[i][j]);  else   printf(" %d", d[i][j]);   }  puts("");}return 0;}


0 0
原创粉丝点击