結果

問題 No.217 魔方陣を作ろう
ユーザー pekempeypekempey
提出日時 2016-12-23 01:16:25
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 5,000 ms
コード長 1,984 bytes
コンパイル時間 1,801 ms
コンパイル使用メモリ 177,220 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-21 05:48:21
合計ジャッジ時間 3,397 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> oddMagicSquare(int n) {
	assert(n % 2 == 1);
	vector<vector<int>> a(n, vector<int>(n));
	int y = 0;
	int x = n / 2;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			a[y][x] = i * n + j + 1;
			x = (x + 1) % n;
			y = (y + n - 1) % n;
		}
		x = (x + n - 1) % n;
		y = (y + 2) % n;
	}
	return a;
}

vector<vector<int>> fourMagicSquare(int n) {
	assert(n % 4 == 0);
	vector<vector<int>> a(n, vector<int>(n));
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (((i + 1) / 2 + (j + 1) / 2) % 2 == 0) {
				a[i][j] = i * n + j + 1;
			} else {
				a[n - 1 - i][n - 1 - j] = i * n + j + 1;
			}
		}
	}
	return a;
}

vector<vector<int>> fourTwoMagicSquare(int n) {
	assert(n % 4 == 2);
	auto b = oddMagicSquare(n / 2);
	for (int i = 0; i < n / 2; i++) {
		for (int j = 0; j < n / 2; j++) {
			b[i][j] = (b[i][j] - 1) * 4;
		}
	}
	vector<vector<int>> L = { { 4, 1 }, { 2, 3 } };
	vector<vector<int>> U = { { 1, 4 }, { 2, 3 } };
	vector<vector<int>> X = { { 1, 4 }, { 3, 2 } };
	vector<vector<int>> a(n, vector<int>(n));
	for (int i = 0; i < n / 2; i++) {
		for (int j = 0; j < n / 2; j++) {
			vector<vector<int>> A;
			if (i < n / 4) {
				A = L;
			} else if (i == n / 4) {
				if (j == n / 4) {
					A = U;
				} else {
					A = L;
				}
			} else if (i == n / 4 + 1) {
				if (j == n / 4) {
					A = L;
				} else {
					A = U;
				}
			} else {
				A = X;
			}
			for (int ii = 0; ii < 2; ii++) {
				for (int jj = 0; jj < 2; jj++) {
					a[i * 2 + ii][j * 2 + jj] = b[i][j] + A[ii][jj];
				}
			}
		}
	}
	return a;
}

vector<vector<int>> magicSquare(int n) {
	if (n % 2 == 1) {
		return oddMagicSquare(n);
	} else if (n % 4 == 0) {
		return fourMagicSquare(n);
	} else {
		return fourTwoMagicSquare(n);
	}
}

int main() {
	int n;
	cin >> n;

	auto a = magicSquare(n);

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			cout << a[i][j] << " ";
		}
		cout << endl;
	}
}
0