1050 螺旋矩阵 (25 分)
本题要求将给定的 N 个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第 1 个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为 m 行 n 列,满足条件:m×n 等于 N;m≥n;且 m−n 取所有可能值中的最小值。
输入格式:
输入在第 1 行中给出一个正整数 N,第 2 行给出 N 个待填充的正整数。所有数字不超过 104,相邻数字以空格分隔。
输出格式:
输出螺旋矩阵。每行 n 个数字,共 m 行。相邻数字以 1 个空格分隔,行末不得有多余空格。
输入样例:
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 <cstdio>
#include <algorithm>
using namespace std;
int cmp(int a, int b){
return a > b;
}
int main()
{
int N = 0, a[10010];
scanf("%d", &N);
for (int i = 0; i < N; i++){
scanf("%d", &a[i]);
}
sort(a, a + N,cmp);
int m = 0, n = 0, min=10000000, x = 0, y = 0;
for (int i = 1; i <= N; i++){
x = i;
y = N / x;
if (x * y == N && x - y < min&&x >= y){
m = x, n = y;
min = x - y;
}
}
int m1 = 0, n1 = 0, arr = 0, c[10000][200], m2 = m, n2 = n; //二维数组行数一定要为10010,不然在提交时会提示段错误,太大也会提示段错误
while (arr < N)
{
for (int i = n1; i < n&&arr<N; i++)
{
c[m1][i] = a[arr];
arr++;
}
m1++;
for (int i = m1; i < m&&arr<N; i++)
{
c[i][n-1] = a[arr];
arr++;
}
n--;
for (int i = n - 1; i >= n1&&arr<N; i--)
{
c[m-1][i] = a[arr];
arr++;
}
m--;
for (int i = m - 1; i >= m1&&arr<N; i--)
{
c[i][n1] = a[arr];
arr++;
}
n1++;
}
for (int i = 0; i < m2; i++)
{
for (int j = 0; j < n2; j++)
{
printf("%d", c[i][j]);
if (j != n2 - 1) printf(" ");
}
printf("\n");
}
}