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: 70ms
Memory: 1136kB
Author: 2018212212225
In contest: 1277

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
int main(){
	int f(int N);
	int comp(const void*p,const void*q);
	int t;
	scanf("%d",&t);
	while(t--){
		int ai[10010];
		int  matrix[10000] = {0};
		int N;
		int m,n;
		int x = -1, y = 0, index = 0;
		scanf("%d",&N);
		for(int i=0;i<N;++i){
			scanf("%d",&ai[i]);
		}
		qsort(ai,N,sizeof(int),comp);
		m=f(N);
		n=N/m;
		int horizontal = n, virtical = m;
		while(horizontal > 0 && virtical > 0)
		{
			for(int i = 0; i < horizontal && virtical > 0; i++)  /* 向右 */
				matrix[y * n + ++x] = ai[index++];
			virtical--;
			for(int i = 0; i < virtical && horizontal > 0; i++)  /* 向下 */
				matrix[++y * n + x] = ai[index++];
			horizontal--;
			for(int i = 0; i < horizontal && virtical > 0; i++)  /* 向左 */
				matrix[y * n + --x] = ai[index++];
			virtical--;
			for(int i = 0; i < virtical && horizontal > 0; i++)  /* 向上 */
				matrix[--y * n + x] = ai[index++];
			horizontal--;
		}
		for(int i = 0; i < m; i++)
			for(int j = 0; j < n; j++)
				printf("%d%c", matrix[i * n + j], j == n - 1 ? '\n' : ' ');
		printf("\n");
	}
}
int f(int N){
	int m;
	m=(int)sqrt((double)N);
	int minj=N,mini=1,minix=N;
	for(int j=m;j<=N;++j){
		for(int i=j;i>0;--i){
			if(j*i==N){
				if(j-i<minix){
					minix=j-i;
					minj=j;
					mini=i;
				}
				break;
			}
		}
	}
	return minj;
}
int comp(const void*p,const void*q){
	return (*(int*)q-*(int*)p);
}