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: 64ms
Memory: 5280kB
Author: 2018212212175
In contest: 1289

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm> 
using namespace std; 
const int maxn = 1e4 + 11;
int sum[maxn]; 
int ans[maxn][105]; 
bool cmp(const int &a, const int &b)
{ 	
	return a > b; 
} 
int fa[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };
int main()
{ 	
	int t, n; 	
	int h, l, len; 
	scanf("%d", &t); 
	int x; 	
	while (t--)
	{ 	
		len = 1; 	
		memset(ans, 0, sizeof ans); 
		scanf("%d", &n); 		
		x = (int)sqrt(n); 
		for (int i = x; i >= 1; i--) 
		{ 			
			if (n%i == 0) 
			{ 			
				l = i; 			
				h = n / i; 		
				break; 		
			} 		
		} 	
		for (int i = 1; i <= n; i++)
		{ 			
			scanf("%d", &sum[i]); 		
		} 	
		sort(sum + 1, sum + n + 1, cmp); 	
		int f = 0; 		
		int i = 1, j = 1; 	
		int di, dj; 	
		ans[i][j] = sum[len++]; 	
		while (len != n + 1)
		{ 			
			di = i + fa[f][0]; 		
			dj = j + fa[f][1]; 		
			if (di <= h && di >= 1 && dj <= l && dj >= 1 && ans[di][dj] == 0) 
			{ 			
				ans[di][dj] = sum[len++]; 	
				i = di, j = dj; 			
			} 		
			else
			{ 			
				f++; 		
				f %= 4; 		
			} 		
		} 		
		for (int i = 1; i <= h; i++)
		{ 		
			for (int j = 1; j <= l; j++)
			{ 			
				if (j != l) printf("%d ", ans[i][j]); 		
				else printf("%d\n", ans[i][j]); 		
			} 		
		} 		
		
		printf("\n"); 
	} 
}