Result: Accepted
Time: 37ms
Memory: 5964kB
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#define INF 0x3f3f3f3f
#define lowbit(x) (x&(-x))
using namespace std;
typedef long long ll;
const int maxn = 1e4+7;
int arr[maxn],mtx[10007][107];
int main()
{
int t,N,n,m,i=0;
scanf("%d",&t);
while(t--)
{
i = 0;
scanf("%d",&N);
n = sqrt(N*1.0);
while(N%n) n--;
m = N/n;
for(int i=0;i<N;i++) scanf("%d",&arr[i]);
sort(arr,arr+N,greater<int>());
arr[N] = 0;
int pos = 0;
int cot = 0;
while(pos < N)
{
for(int j=cot;j<n-cot && pos<N;j++)
mtx[cot][j] = arr[pos++];
for(int j=cot+1;j<m-cot && pos<N;j++)
mtx[j][n-1-cot] = arr[pos++];
for(int j=n-2-cot;j>=cot && pos<N;j--)
mtx[m-1-cot][j] = arr[pos++];
for(int j=m-2-cot;j>cot && pos<N;j--)
mtx[j][cot] = arr[pos++];
cot++;
}
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
j == n-1 ? printf("%d\n",mtx[i][j]) : printf("%d ",mtx[i][j]);
printf("\n");
}
}