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: 29ms
Memory: 1772kB
Author: 2018212212137
In contest: 1277

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
bool cmp(int a,int b){return a>b;}
int main(){
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int N;scanf("%d",&N);int a[N],m,n;
    for(int i=0;i<N;i++) scanf("%d",&a[i]);
    sort(a,a+N,cmp);
    for(int i=sqrt(N);i>0;i--){
        if(N%i==0){
            n=i;m=N/i;break;
        }
    }
    int matrix[m][n];
    int row=0,col=0,no=0,cir=0;
    while(no<N){
        matrix[row][col]=a[no++];
        if(row==cir&&col<n-1-cir) col++;
        else if(col==n-1-cir&&row<m-1-cir) row++;
        else if(row==m-1-cir&&col>cir) col--;
        else if(col==cir&&row>cir+1) row--;
        else if(col==cir&&row==1+cir){
            col++;cir++;
        }
    }
    for(int i=0;i<m;i++){
        for(int j=0;j<n-1;j++){
            printf("%d ",matrix[i][j]);
        }
        printf("%d\n",matrix[i][n-1]);
       
    }
    printf("\n");
	}
    
    return 0;
}