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: 85ms
Memory: 6108kB
Author: 2018212212059
In contest: 1289

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <set>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <deque>
#define clr(a,b) memset(a,b,sizeof(a))
#define ll long long

using namespace std;

const int maxn=1e4+10;
int t,n;
int a[maxn],ans[maxn][110];

int main()
{
	cin>>t;
	while(t--)
	{
		clr(ans,0),clr(a,0);
		cin>>n;
		for(int i=1;i<=n;i++)cin>>a[i];
		sort(a+1,a+1+n);
		
		//定几行几列 
		int x=n,y=1;
		for(int i=2;i<=sqrt(n*1.0);i++)//列举y 
		{
			if(n%i==0)
			{
				x=n/i;
				y=i;
			}
		}
		
		//填充 
		int now=n,dx=1,dy=0;
		while(1)
		{
			while(dy+1<=y&&!ans[dx][dy+1])//right
			{
				ans[dx][++dy]=a[now];
				now--;
				if(!now)break;
			}
			if(!now)break;
			while(dx+1<=x&&!ans[dx+1][dy])//down
			{
				ans[++dx][dy]=a[now];
				now--;
				if(!now)break;
			}
			if(!now)break;
			while(dy-1>=1&&!ans[dx][dy-1])//left
			{
				ans[dx][--dy]=a[now];
				now--;
				if(!now)break;
			}
			if(!now)break;
			while(dx-1>=1&&!ans[dx-1][dy])//up
			{
				ans[--dx][dy]=a[now];
				now--;
				if(!now)break;
			}
			if(!now)break;
		}
		
		for(int i=1;i<=x;i++)
		{
			int k=0;
			for(int j=1;j<=y;j++)
			{
				if(k)cout<<" ";
				cout<<ans[i][j];
				k=1;
			}
			puts("");
		}
		puts("");
	}
}