Educational Codeforces Round 16-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
1
output
1
input
3
output
2 1 4
3 5 7
6 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 1000000007
typedef 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;	
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章