PAT乙1050 螺旋矩阵 数组范围

1050 螺旋矩阵(25)(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

矩阵b不止b[105][105]
但是b[10005][10005]最后一个测试点会内存超限
由于m>=n,m 边界为10000,n 边界为100;所以取b[10005][105]

做法:将数a填入矩阵b

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
int N,m,n,a[10005],b[10005][105];//注意b边界并不是sqrt(100005);
int main()
{
    scanf("%d",&N);
    m=n=sqrt(N);
    while(m*n!=N)
    {
        if(m*n<N)m++;
        else     n--;
    }
    for(int i=0;i<N;i++)
    {
        scanf("%d",&a[i]);
    }
    sort(a,a+N);
    int x=0,y=0,dir=0,t=0;
    for(int i=N-1;i>=0;i--)
    {
        b[x][y]=a[i];
        //change
        if(dir==0)
        {
            if(y<n-1-t)y++;
            else{dir=1;x++;} 
        }
        else if(dir==1)
        {
            if(x<m-1-t)x++;
            else{dir=2;y--;}
        }
        else if(dir==2)
        {
            if(y>t)y--;
            else{dir=3;x--;}
        }
        else if(dir==3)
        {
            if(x>1+t)x--;
            else{dir=0;y++;t++;}
        }
    }
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n-1;j++)
        {
            printf("%d ",b[i][j]);
        }
        printf("%d\n",b[i][n-1]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40367307/article/details/81301046