Start: Jul, 01, 2019 08:30:00
2019年度暑期短学期第四天
End: Jul, 01, 2019 11:30:00
Time elapsed:
Time remaining:

Problem_ID: B
Result: Accepted
Time: 71ms
Memory: 1120kB
Author: 2018212212245
In contest: 1277

#include<stdio.h>
#include<stdlib.h>

int comp(const void *a, const void *b)
{
	return *(int *)b - *(int *)a;
}
int main()
{
    int T, N, m, n, i, j, k, t;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%d", &N);
		int a[N];
		for (i = 0; i < N; i++)
		{
			scanf("%d", &a[i]);
		}
		qsort(a, N, sizeof(int), comp);
		k = 10001;
		for (i = 1; i <= N; i++)
		{
			for (j = 1; j <= N; j++)
			{
				if (i * j == N && i >= j && k >= i - j)
				{
					m = i, n = j;
					k = i - j;
				}
			}
		}
		int b[m][n];
		t = 0;
		for (i = 0; i < (n / 2 + n % 2); i++)
		{
			for (j = i; j <= n - i - 1 && t <= N - 1; j++)
			{
				b[i][j] = a[t++];
			}
			for (j = i + 1; j <= m - i - 2 && t <= N - 1; j++)
			{
				b[j][n - i - 1] = a[t++];
			}
			for (j = n - i - 1; j >= i && t <= N - 1; j--)
			{
				b[m - i - 1][j] = a[t++];
			}
			for (j = m - i - 2; j >= i + 1 && t <= N - 1; j--)
			{
				b[j][i] = a[t++];
			}
		}
		for (i = 0; i < m; i++)
		{
			for (j = 0; j < n; j++)
			{
				printf("%d", b[i][j]);
				if (j != n - 1)
				{
					printf(" ");
				}
			}
			printf("\n");
		}
		printf("\n");
	}
	
	return 0;
}