PAT-乙级-1050. 螺旋矩阵(25)

1050. 螺旋矩阵(25)

时间限制
150 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue

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

输入格式:

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

输出格式:

输出螺旋矩阵。每行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
 1 #include<bits/stdc++.h>
 2 using namespace std; 
 3 int a[10000][10000]={0},s[10000]; 
 4 bool cmp(int a,int b){
 5     return a>b;
 6 }
 7 int main(){
 8     int n,i,j,x,y,r,c,tot,minn=9999;
 9    
10     scanf("%d",&n);
11     for(int i=0;i<n;i++)
12     scanf("%d",&s[i]);
13     sort(s,s+n,cmp);
14     for(i=1;i<=sqrt(n*1.0);i++)
15     {
16         if(n%i==0)
17         {
18             if(n/i-i<minn){
19                 minn=n/i-i;
20                 r=i;
21             }
22         }        
23     }
24     c=n/r;//c>r c行r列 
25     a[0][0]=s[0];
26     tot=x=y=0;
27     while(tot < r * c-1)
28     {
29         while(y + 1 < r && ! a[x][y + 1])
30             a[x][++y] = s[++tot];
31         while(x + 1 < c && !a[x + 1][y])
32             a[++x][y] = s[++tot];
33         while(y - 1 >= 0 && !a[x][y - 1])
34             a[x][--y] = s[++tot];
35         while(x - 1 >= 0 && !a[x - 1][y])
36             a[--x][y] = s[++tot];   
37     }
38     for(i=0;i<c;i++){
39             printf("%d",a[i][0]);
40         for(j=1;j<r;j++){
41                 printf(" %d",a[i][j]);
42         } 
43         printf("
");
44         
45     }
46     return 0;
47 }
原文地址:https://www.cnblogs.com/zhien-aa/p/5671115.html