1 题目
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 10
4
. 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
Sample Output:
98 95 93
42 37 81
53 20 76
58 60 76
2 解析
2.1 题意
模拟输出非递增的顺时针螺旋矩阵,矩阵的行数大于列数,且行数乘以列数要等于元素个数,且m-n最小
2.2 思路
- 1 求矩阵的行m和列n
- 题目要求行数要大于列数,且行数和列数之差最小;
- 当元素个数N为素数时,行数=N,列数=1;
- 当元素个数N为完全二次方数时,行数= N \sqrt{N} N=列数;
- 因此行数m最小为 N \sqrt{N} N,列数n最小为1;
- 为了使得m和n差值最小,因此枚举行数m,从 N \sqrt{N} N开始递增枚举,直到N可以整除m,此时n为N\m(或者枚举列数n,从从 N \sqrt{N} N开始递减枚举);
- 2 模拟填充矩阵,设矩阵的上下左右的边界分别为U= 1, D = m,L = 1,R = n,填充坐标为(x= 1,y = 0);(输出的数组元素下标从1开始,方便计算)
- 从 左上角开始填充(边填充边缩小矩阵的大小),同时统计填充的个数num:
- 首先向右填充,当x==R时,上边界U加1,向下填充;
- 当y==D时,右边界减1,,向左填充;
- 当x==L时,下边界加1,向上填充;
- 当y==D时,左边界加1;
- 当num小于等于N时,不断执行上面四个步骤。
- 3 特殊情况特殊处理,当N为1时,直接输出,当N为素数时,排序后,由于列数为1,于是直接输出就可以(每输出一个元素,换一行)。
3 参考代码
#include <cstdio>
#include <algorithm>
#include <cmath>
using std::sort;
const int MAXN = 10010;
int A[MAXN];
int matrix[MAXN][MAXN];
bool cmp(int a, int b){
return a > b;
}
int main(int argc, char const *argv[])
{
int N;
scanf("%d", &N);
for (int i = 1; i <= N; ++i)
{
scanf("%d", &A[i]);
}
if(N == 1){
printf("%d", A[1]);
return 0;
}
sort(A + 1, A + N + 1, cmp);
int m, n;
for (int i = ceil(sqrt(1.0 * N)); i <= N; ++i)
{
if(N % i == 0){
m = i;
n = N / i;
break;
}
}
if(n == 1){
for (int i = 1; i <= N; ++i) {
printf("%d\n", A[i]);
}
}else{
int U = 1, D = m, L = 1, R = n;
int num = 1;
int x = 1, y = 0;
while(num <= N){
while(num <= N && y < R){
matrix[x][++y] = A[num++];
}
U += 1;
while(num <= N && x < D){
matrix[++x][y] = A[num++];
}
R -= 1;
while(num <= N && y > L){
matrix[x][--y] = A[num++];
}
D -= 1;
while(num <= N && x > U){
matrix[--x][y] = A[num++];
}
L += 1;
if(num == N){
matrix[x][y + 1] = A[num];
num++;
}
}
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
printf("%d", matrix[i][j]);
if(j < n) printf(" ");
}
printf("\n");
}
}
return 0;
}