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: 46ms
Memory: 6268kB
Author: 2018212212122
In contest: 1277

#include <cstdio>
#include <iostream>
#include<cmath>
#include<algorithm>
using namespace std;
int n,m,t;
int i,j,k;
const int maxn=1e4+10; 
int s[maxn][114];
int a[maxn];
int coutt,c;
int dir[4][2]={1,0,0,1,-1,0,0,-1};
bool cmp(const int a,const int b){
	return a>b;
}
void fun(int n,int m){
	int p=m+n-1;
	c=coutt=1;
	if(c<=c+n-1&&c<=m+n){//上
		for(j=coutt;j<=m;++j){
			s[coutt][j]=a[p];
			p--;
			c++;
		}
	}
	if(c<=c+m-2&&c<=m+n){//右
		for(i=coutt+1;i<=m-1;++i){
			s[i][n]=a[p];
			p--;
			c++;
		}
	}
	if(c<=c+n-2&&c<=m+n){
		for(j=n;j>=coutt;j--){
			s[n][j]=a[p];
			p--;
			c++;
		}
	}
	if(c<=c+m-3&&c<=m+n){
		for(i=m-1;i>=coutt+1;i--){
			s[i][coutt]=a[p];
			p--;
			c++;
		}
	}
	coutt++;
	if(c<=m+n)
		fun(n-1,m-1);
	else
		for(i=1;i<=n;++i){
			for(j=1;j<=m;++j)
			{
				printf("%d ",s[i][j]);
			}
			printf("\n");
		}
}
int main()
{
	int N;
	scanf("%d",&t);
	while(t--){
		scanf("%d",&N);
		for(i=0;i<N;++i){
			scanf("%d",&a[i]);
		}
		sort(a,a+N,cmp);
		int mm,nn;
		/*for(m=N;m>0;--m){
			for(n=0;n<N;++n){
				if(N>m-n&&m-n>0){
					N=m-n;
					mm=n,nn=m;
				}
			}
		}*/
		for(n=ceil(sqrt(N*1.0));;++n){
			if(N%n==0){
				m=N/n;
				break;
			}
		}
		for(i=0;i<n;++i)
			for(j=0;j<m;++j)
				s[i][j]=0;
		k=i=j=0;
		int kk=0;
		while(k!=n*m){
			s[i][j]=a[k];
			int ii=i+dir[kk][1],jj=j+dir[kk][0];
			if(!(ii>=0&&jj>=0&&ii<n&&jj<m&&s[ii][jj]==0))
				kk=(kk+1)%4;
			i+=dir[kk][1],j+=dir[kk][0];
			++k;
		}
		for(i=0;i<n;++i)
			for(j=0;j<m;++j)
				printf("%d%c",s[i][j]," \n"[j==m-1]);
		//fun(nn,mm);
		printf("\n");
	}
	return 0;
}