PTA 螺旋矩阵 (25分)

“人其实就这一辈子,我想要的生活不是安逸的,虽然很累,但我想要辉煌的人生,所以也一直在为此努力、不松懈。我所理解的辉煌人生,不是挣了多少钱、做了多伟大的事,而是将人生过得有意义,不碌碌无为。哪怕前进得很慢,但是每分每秒都在往前走,去追求梦想。”                                                                                                                               ----喻言

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

输入格式:

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

输出格式:

输出螺旋矩阵。每行 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 <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <ctime>
#include <cctype>
#include <bitset>
#include <utility>
#include <sstream>
#include <complex>
#include <iomanip>
#include <numeric>
#include<unordered_set>
#include <climits>//INT_100010n
//#include<bits/stdc++.h>
#define PP pair<ll,int>
#define inf 0x3f3f3f3f
#define INF 0x7fffffff;
#define llinf 0x3f3f3f3f3f3f3f3fll
#define dinf 1000000000000.0
#define PI 3.1415926
#define LL unsigned int
#define mod 1000000007
#define wc 1e-8
typedef long long ll;
using namespace std;
int n;
int main()
{
    scanf("%d",&n);
    int a[n];
    for(int i=0; i<n; i++)
        scanf("%d",&a[i]);
    sort(a,a+n);
    int x=sqrt(n),m;
    while(n%x)
    {
        x--;
    }
    m=n/x;
    int t[m][x];
    for(int ls=0,k=n-1; ls*2<x; ls++)
    {
        for(int j=ls; j<x-ls; j++)
            t[ls][j]=a[k--];
        for(int i=ls+1; i<m-ls; i++)
            t[i][x-1-ls]=a[k--];
        for(int j=x-2-ls; j>=ls; j--)
            t[m-1-ls][j]=a[k--];
        if(x-1-ls>ls)
        {
            for(int i=m-2-ls; i>=ls+1; i--)
            {
                t[i][ls]=a[k--];
            }
        }
    }
    for(int i=0; i<m; i++)
    {
        for(int j=0; j<x; j++)
        {
            printf("%d",t[i][j]);
            if(j+1<x)
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值