【题解】PATB-1050 螺旋矩阵

螺旋矩阵 (PATB-1050)

题面

本题要求将给定的 N 个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第 1 个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为 m 行 n 列,满足条件:m×n 等于 N;m≥n;且 m−n 取所有可能值中的最小值。

输入

输入在第 1 行中给出一个正整数 N,第 2 行给出 N 个待填充的正整数。所有数字不超过 10^4,相邻数字以空格分隔。

输出

输出螺旋矩阵。每行 n 个数字,共 m 行。相邻数字以 1 个空格分隔,行末不得有多余空格。

样例输入

1
2
12
37 76 20 98 76 42 53 95 60 81 58 93

样例输出

1
2
3
4
98 95 93
42 37 81
53 20 76
58 60 76

提示

思路

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const int mxn = 1e5 + 5;
int a[mxn], ans[mxn];

int main()
{
int t; scanf("%d", &t);

int n, m;
for(int i=sqrt(t); i; i--){
if(t%i == 0){
m = i;
n = t/m;
break;
}
}
for(int i=0; i<t; i++)
scanf("%d", &a[i]);
sort(a, a+t);

int x=0, y=-1;
for(t--; t>=0;)
{
while(y+1<m && *(ans+x*m+y+1) == 0){
++y; *(ans+x*m+y) = a[t--];
}

while(x+1<n && *(ans+(x+1)*m+y) == 0){
++x; *(ans+x*m+y) = a[t--];
}

while(y-1>=0 && *(ans+x*m+y-1) == 0){
--y; *(ans+x*m+y) = a[t--];
}

while(x-1>=0 && *(ans+(x-1)*m+y) == 0){
--x; *(ans+x*m+y) = a[t--];
}
}

for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(j) printf(" ");
printf("%d", *(ans+i*m+j));
}
printf("\n");
}

return 0;
}