結果

問題 No.217 魔方陣を作ろう
ユーザー masamasa
提出日時 2015-05-27 00:15:45
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 2 ms / 5,000 ms
コード長 1,904 bytes
コンパイル時間 569 ms
コンパイル使用メモリ 70,328 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-20 15:25:14
合計ジャッジ時間 1,663 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 2 ms
4,380 KB
testcase_08 AC 2 ms
4,380 KB
testcase_09 AC 1 ms
4,376 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 2 ms
4,376 KB
testcase_12 AC 1 ms
4,376 KB
testcase_13 AC 2 ms
4,380 KB
testcase_14 AC 2 ms
4,376 KB
testcase_15 AC 2 ms
4,380 KB
testcase_16 AC 1 ms
4,376 KB
testcase_17 AC 2 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <utility>
#include <string>

using namespace std;

typedef vector<int>   VI;
typedef vector< VI > VVI;

int n, n2;
VVI ms;

void show(int n, VVI &vec) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			printf("%3d ", vec[i][j]);
		}
		printf("\n");
	}
}

VVI makeOddMS(int len) {
	VVI magic(n, VI(n, 0));
	int x = len / 2;
	int y = 0;
	int len2 = len * len;
	int nx, ny;
	for (int i = 1; i <= len2 ; i++) {

		magic[y][x] = i;


		nx = (x + 1) % len;
		ny = (y - 1 + len) % len;
		if (magic[ny][nx] == 0) {
			x = nx;
			y = ny;
		} else {
			y++;
		}
	}
	return magic;
}

int main() {

	cin >> n;
	n2 = n * n;
	ms.assign(n, vector<int>(n, 0));

	if (n % 2 == 1) {
		ms = makeOddMS(n);
	} else if (n % 4 == 0) {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				int x = j % 4;
				int y = i % 4;
				if (x == y || (x + y) % 4 == 3) {
					ms[j][i] = i * n + j + 1;
				} else {
					ms[n - 1 - j][n - 1 - i] = i * n + j + 1;
				}
			}
		}

	} else {
		int a, b, c, d;
		int n_half = n / 2;
		auto ms1 = makeOddMS(n_half);
		for (int i = 0; i < n_half; i++) {
			for (int j = 0; j < n_half; j++) {
				ms1[i][j] = (ms1[i][j] - 1) * 4;
			}
		}

		int center = n_half / 2;
		for (int i = 0; i < n_half; i++) {
			for (int j = 0; j < n_half; j++) {
				if (i >= center + 2) {
					a = 1;
					b = 4;
					c = 3;
					d = 2;
				} else if ((i == center + 1 && j != center) ||
				           (i == center     && j == center)
				           ) {
					a = 1;
					b = 4;
					c = 2;
					d = 3;
				} else {
					a = 4;
					b = 1;
					c = 2;
					d = 3;
				}

				ms[i * 2 + 0][j * 2 + 0] = ms1[i][j] + a;
				ms[i * 2 + 0][j * 2 + 1] = ms1[i][j] + b;
				ms[i * 2 + 1][j * 2 + 0] = ms1[i][j] + c;
				ms[i * 2 + 1][j * 2 + 1] = ms1[i][j] + d;
			}
		}
	}

	show(n, ms);


	return 0;
}
0