結果

問題 No.217 魔方陣を作ろう
ユーザー くれちーくれちー
提出日時 2016-12-29 23:10:54
言語 C90
(gcc 11.4.0)
結果
AC  
実行時間 1 ms / 5,000 ms
コード長 1,812 bytes
コンパイル時間 224 ms
コンパイル使用メモリ 26,876 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-22 00:11:07
合計ジャッジ時間 1,288 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include <stdio.h>
#include <stdbool.h>
#define rep(i, n) for (i = 0; i < n; i++)
#define rrep(i, n) for (i = n; i >= 0; i--)

// (2n+1)x(2n+1) (ヒンズーの連続方式)
void solve1(int ans[20][20], int n) {
	int x = n / 2, y = 0, t = 1;
	while (t <= n * n) {
		while (1) {
			while (x < 0) x += n;
			while (x >= n) x -= n;
			while (y < 0) y += n;
			while (y >= n) y -= n;
			if (ans[x][y] != 0) { x--; y += 2; }
			else break;
		}
		ans[x++][y--] = t++;
	}
}

// 4x4
void solve2(int ans[20][20], int n) {
	int i, j;
	int t1 = 1, t2 = n * n;
	rep(i, n) rep(j, n) {
		bool f1 = i % 4 == 0 || (i + 1) % 4 == 0;
		bool f2 = j % 4 == 0 || (j + 1) % 4 == 0;
		if ((f1 && f2) || (!f1 && !f2)) ans[i][j] = t1;
		else ans[i][j] = t2;
		t1++; t2--;
	}
}

// (4n+2)x(4n+2) (LUX法)
void solve3(int ans[20][20], int n) {
	int i, j, k, l;
	int t1[20][20] = {}, t2[20][20], tn = n / 2;
	int lm[2][2] = { { 4,2 },{ 1,3 } };
	int um[2][2] = { { 1,2 },{ 4,3 } };
	int xm[2][2] = { { 1,3 },{ 4,2 } };
	enum { L, U, X };
	solve1(t1, tn);
	rep(i, tn) rep(j, tn) {
		t1[i][j]--; t1[i][j] *= 4;
		if (i == tn / 2 && j == tn / 2) t2[i][j] = U;
		else if (i == tn / 2 && j == tn / 2 + 1) t2[i][j] = L;
		else if (j == tn / 2 + 1) t2[i][j] = U;
		else if (j < tn / 2 + 1) t2[i][j] = L;
		else t2[i][j] = X;
	}
	for (i = 0; i < n; i += 2) for (j = 0; j < n; j += 2) {
		int t3 = t1[i / 2][j / 2], t4;
		rep(k, 2) rep(l, 2) {
			if (t2[i / 2][j / 2] == L) t4 = lm[k][l];
			else if (t2[i / 2][j / 2] == U) t4 = um[k][l];
			else t4 = xm[k][l];
			ans[i + k][j + l] = t3 + t4;
		}
	}
}

int main() {
	int n;
	scanf("%d", &n);

	int ans[20][20] = {}, i, j;
	if (n % 2 == 1) solve1(ans, n);
	else if (n % 4 == 0) solve2(ans, n);
	else solve3(ans, n);

	rep(i, n) {
		rep(j, n) printf("%d ", ans[i][j]);
		printf("\n");
	}
	return 0;
}
0