1105 Spiral Matrix (25 分)

本文详细解析了螺旋矩阵填充算法,介绍了如何将一系列正整数按逆时针螺旋顺序填入矩阵,确保矩阵的行数大于等于列数且两者之差最小。通过实例演示了算法的实现过程,包括输入序列的排序、矩阵边界的设定及螺旋填充的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 关于螺旋矩阵的问题:可以一层一层的去解决,先将数组从大到小排序  设置矩阵的边界条件,上为u. 下为d  左为l  右为r 一层一层去填写, 一层填写完成后,u++ d-- l++ r-- . 最先要算出矩阵的规模 ,要求m行n列,m>=n m-n最小,那么m n都肯定是其因子, 故可求出数字的开方的上界, 往上++,直到N%m==0 此时m-n最小。注意只有一个元素时,直接输出。

#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include<vector>
#include<set>
#include<map>
#include<unordered_map>
#include<queue>
#include<algorithm>
#include<cmath>
using namespace std;
#define ll long long
#define vi vector<int>
#define pii pair<int, int>
#define x first
#define y second
const int maxn=11000;
bool cmp(int a,int b)
{
    return a>b;
}
int mar[maxn][maxn],n,ans[maxn];
int main()
{
    cin>>n;
    for(int i=0;i<n;i++) cin>>ans[i];
    if(n==1) {printf("%d",ans[0]); return 0;}
    sort(ans,ans+n,cmp);
    int m=(int)ceil(sqrt(1.0*n));
    while(n%m!=0) m++;
    int c=n/m, i=1,j=1,now=0;
    int u=1,d=m,l=1,r=c;
    while(now<n)
    {
        while(now<n&&j<r)
        {
            mar[i][j]=ans[now++];
            j++;
        }
        while(now<n&&i<d)
        {
            mar[i][j]=ans[now++];
            i++;
        }
        while(now<n&&j>l)
        {
            mar[i][j]=ans[now++];
            j--;
        }
        while(now<n&&i>u)
        {

            mar[i][j]=ans[now++];
            i--;
        }
        u++;d--;l++;r--;
        i++;j++;
        if(now==n-1)
        {

             mar[i][j]=ans[now++];
        }

    }
    for(int i=1;i<=m;i++)
    {
        for(int j=1;j<=c;j++)
        {
          if(j<c) cout<<mar[i][j]<<" ";
          else cout<<mar[i][j]<<endl;
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值