PAT刷题:1050. 螺旋矩阵(25)

来源:互联网 发布:手机淘宝怎么样找客服 编辑:程序博客网 时间:2024/06/07 02:08

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

输入格式:

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

输出格式:

输出螺旋矩阵。每行n个数字,共m行。相邻数字以1个空格分隔,行末不得有多余空格。

输入样例:
1237 76 20 98 76 42 53 95 60 81 58 93
输出样例:
98 95 9342 37 8153 20 7658 60 76
#include <iostream>#include <cmath>#include <vector>#include <algorithm>using namespace std;bool cmp(const int &a,const int &b){    return a>b;}int main(){    int cnt=0;    cin>>cnt;    int t = sqrt(cnt);    while(cnt%t!=0)t--;    int n=t;    int m=cnt/t;    vector<int> nums;    nums.resize(cnt);    for(int i=0;i<cnt;i++){        int temp=0;        cin>>temp;        nums[i]=temp;    }    sort(nums.begin(),nums.end(),cmp);    int output[m][n];    for(int i=0;i<m;i++)for(int j=0;j<n;j++)output[i][j]=-1;    int dx=1,dy=0;    int x=0,y=0;    for(int i=0;i<cnt;i++){        output[y][x]=nums[i];        if(x==0&&y==0){dx=1;dy=0;}        else if(x==(n-1)&&y==0){dx=0;dy=1;}        else if(x==(n-1)&&y==(m-1)){dx=-1;dy=0;}        else if(x==0&&y==(m-1)){dx=0;dy=-1;}        else if(output[y+dy][x+dx]!=-1){            if(dx==1&&dy==0){dx=0;dy=1;}            else if(dx==0&&dy==1){dx=-1;dy=0;}            else if(dx==-1&&dy==0){dx=0;dy=-1;}            else if(dx==0&&dy==-1){dx=1;dy=0;}        }        x+=dx;        y+=dy;    }    for(int i=0;i<m;i++)    {        for(int j=0;j<n;j++)        {            cout<<output[i][j];            if(j<(n-1))cout<<" ";        }        cout<<endl;    }    return 0;}