PAT 1050 螺旋矩阵

https://pintia.cn/problem-sets/994805260223102976/problems/994805275146436608

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

输入格式:

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

输出格式:

输出螺旋矩阵。每行 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<bits/stdc++.h>
using namespace std;

int a[10000][1000], s[10000];

bool cmp(int a, int b){
    return a > b;
}

int main() {
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i ++)
    scanf("%d", &s[i]);
    sort(s, s + n, cmp);

    int r, c;
    int minn = 99999;
    for(int i = 1; i <= sqrt(n * 1.0); i ++) {
        if(n % i == 0) {
            if(n / i - i < minn) {
                minn = n / i - i;
                r = i;
            }
        }
    }
    c = n / r;

    a[1][1] = s[0];
    int tot = 0;
	int x = 1, y = 1;
    while(tot < r * c - 1) {
        while(y + 1 <= r && ! a[x][y + 1])
            a[x][++ y] = s[++ tot];
        while(x + 1 <= c && !a[x + 1][y])
            a[++ x][y] = s[++ tot];
        while(y - 1 > 0 && !a[x][y - 1])
            a[x][-- y] = s[++ tot];
        while(x - 1 > 0 && !a[x - 1][y])
            a[-- x][y] = s[++ tot];
    }

    for(int i = 1; i <= c; i ++){
        printf("%d", a[i][1]);
        for(int j = 2; j <= r; j ++)
            printf(" %d", a[i][j]);
        printf("
");

    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/zlrrrr/p/9709686.html