Start: Jun, 28, 2019 13:00:00
2019年度暑期短学期第四天-助教场
End: Jun, 30, 2019 23:59:00
Time elapsed:
Time remaining:

Problem_ID: B
Result: Accepted
Time: 52ms
Memory: 5968kB
Author: 2018212212127
In contest: 1289

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cstdio>
using namespace std;
typedef long long ll;
const int maxn=1e4+10;
int a[maxn][107],b[maxn];
int dir[4][2]={1,0,0,1,-1,0,0,-1};
struct rule{
	bool operator()(const int &a1,const int &a2){
		return a1>a2;
	}
};
int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		int n,m,N;
		scanf("%d",&N);
		for(int i=0;i<N;i++) scanf("%d",&b[i]);
		sort(b,b+N,rule());
		for(n=ceil(sqrt(N*1.0));;n++){
			if(N%n==0){
				m=N/n;
				break;
			}
		}
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++) a[i][j]=0;
		}
		int k=0,i=0,j=0,kk=0;
		while(k!=n*m){
			a[i][j]=b[k];
			int ii=i+dir[kk][1];
			int jj=j+dir[kk][0];
			if(!(ii>=0&&jj>=0&&ii<n&&jj<m&&a[ii][jj]==0)) kk=(kk+1)%4;
			i+=dir[kk][1];
			j+=dir[kk][0];
			k++;
		}
		for(int ii=0;ii<n;ii++){
			for(int jj=0;jj<m;jj++) printf("%d%c",a[ii][jj]," \n"[jj==m-1]);
		}
		printf("\n");
	}
	
}