# PTA 1105 Spiral Matrix (25 分)

## 1105 Spiral Matrix (25 分)

This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrix is filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and n columns, where m and n satisfy the following: m×n must be equal to N; m≥n; and m−n is the minimum of all the possible values.

### Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains N positive integers to be filled into the spiral matrix. All the numbers are no more than 104. The numbers in a line are separated by spaces.

### Output Specification:

For each test case, output the resulting matrix in m lines, each contains n numbers. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.

### Sample Input:

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

98 95 93
42 37 81
53 20 76
58 60 76

### 感悟

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 10010;
int a[N];
int x, y, res = 0x3f3f3f3f;
int main()
{
int n;
scanf("%d", &n);
for(int i = 1 ; i <= n ; i ++) scanf("%d", &a[i]);
sort(a+1,a+n+1,greater<int>());
for(int i = 1 ; i * i <= n ; i ++)
{
int j = n / i;
if(n % i) continue;
res = min(res,(j-i));
if(res == j - i) x = i, y = j;
}
int b[y+1][x+1] ={0};
int cnt = 1, l = 1;
while(cnt <= n)
{
int lx = x - l,ly = y - l;
for(int i = l ; i <= x ; i ++)
if(!b[l][i]) b[l][i] = a[cnt++];
for(int i = 1 ; i <= y ; i ++)
if(!b[i][x-l+1]) b[i][x-l+1] = a[cnt++];
for(int i = x-l+1 ; i >= 1 ; i --)
if(!b[y-l+1][i]) b[y-l+1][i] = a[cnt++];
for(int i = y-l+1 ; i >= 1 ; i --)
if(!b[i][l]) b[i][l] = a[cnt++];
l++;
}
for(int i = 1 ;i <= y ; i ++)
for(int j = 1 ; j <= x ; j ++)
printf("%d%c",b[i][j],j == x ? '\n' : ' ');

return 0;
}

posted @ 2022-03-03 13:54  别问了我什么都不会  阅读(6)  评论(0编辑  收藏  举报