結果

問題 No.217 魔方陣を作ろう
ユーザー hayashitakeruhayashitakeru
提出日時 2018-03-10 05:15:36
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 5,000 ms
コード長 1,338 bytes
コンパイル時間 707 ms
コンパイル使用メモリ 65,476 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-02 00:22:00
合計ジャッジ時間 1,692 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include <iostream>
using namespace std;

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

	auto magicSquare = [=](auto eval) {
		for (int y = 0; y < n; ++y)
		{
			for (int x = 0; x < n; ++x)
			{
				cout << eval(x, y);
				if (x < n - 1)
				{
					cout << ' ';
				}
			}
			cout << endl;
		}
	};
	auto evenMagic = [](int n) {
		return [n, n2 = n * n, xbase = n >> 1, stride = n + 1](int x, int y) {
			int ybase = ((xbase - x) * 2 + n) % n;
			int yadd = (y - ybase + n) % n * stride;
			return ((xbase - x) * n + n2 + yadd) % n2 + 1;
		};
	};

	if (n & 1)
	{
		magicSquare(evenMagic(n));
	}
	else if (n & 2)
	{
		magicSquare([even = evenMagic(n >> 1), halfn = n >> 2](int x, int y) {
			const int halfx = x >> 1;
			const int halfy = y >> 1;
			const bool isSwap = halfx == halfn && (halfy == halfn || halfy == halfn + 1);
			static const int L[][2] = { { 4, 1 },{ 2, 3 } };
			static const int U[][2] = { { 1, 4 },{ 2, 3 } };
			static const int X[][2] = { { 1, 4 },{ 3, 2 } };
			auto m = halfy <= halfn + 1 ? (halfy == halfn + 1) ^ isSwap ? U : L : X;
			const int val = (even(halfx, halfy) - 1) << 2;
			return val + m[y & 1][x & 1];
		});
	}
	else
	{
		magicSquare([n2 = n * n, i = 0](int x, int y) mutable {
			const bool isDiagonal = (x & 3) == (y & 3) || 3 - (x & 3) == (y & 3);
			return isDiagonal ? ++i : n2 - i++;
		});
	}
	return 0;
}
0