1050. Spiral matrix(25)

1050. Spiral matrix(25)

time limit
150 ms
memory limit
65536 kB
code length limit
8000 B
Judgment procedure
Standard
author
CHEN, Yue

This question requires the given N positive integers to be filled into the "spiral matrix" in non-increasing order. The so-called "spiral matrix" refers to starting from the first grid in the upper left corner and filling it in a clockwise spiral direction. The size of the matrix is ​​required to be m rows and n columns, and the conditions are met: m*n is equal to N; m>=n; and mn takes the minimum value among all possible values.

Input format:

The input gives a positive integer N in line 1 and N positive integers to be padded in line 2. All numbers do not exceed 10 4 , and adjacent numbers are separated by spaces.

Output format:

Output the spiral matrix. Each line contains n numbers, for a total of m lines. Adjacent numbers are separated by 1 space, and there must be no extra spaces at the end of the line.

Input sample:
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

Spiral, that is, using four parameters to calibrate the extreme values ​​of the upper, lower, left, and right, and traversing with ij.

#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn=10001;
int b[maxn][maxn]; int a[maxn]; It is right to put it outside in the main function. Inside b[10001][10001] will make an error because it is too large.

bool cmp(int a,int b){
    return a>b;
}
int main(){
    int N;
    scanf("%d",&N);
    int k=sqrt(N);
    for(int i=k;i >=1;i--){
        if(N%i==0){k=i;break;}
    }
    int m,n;
    n=k;
    m=N/k;

    for(int i=0;i <N;i++){
        scanf("%d",&a[i]);
    }
    sort(a,a+N,cmp);

    int t=0,i=0,j=0;
    int you=n-1 ,xia=m-1,zuo=0,shang=0;

        while(i<=you){
            b[j][i]=a[t];
        //    printf("%d %d %d\n",b[j][i],j,i);
            t++;i++;
        }
        if(t==N){break;}
        shang++;j++;i--;
        while(j<=xia){
            b[j][i]=a[t];
        //    printf("%d %d %d\n",b[j][i],j,i);
            t++;j++;
        }
        if(t==N){break;}
        you--;i--;j--;
        while(i>=zuo){
            b[j][i]=a[t];
       //     printf("%d %d %d\n",b[j][i],j,i);
            t++;i--;
        }
        if(t==N){break;}
        xia--;j--;i++;
        while(j>=shang){
            b[j][i]=a[t];
      //      printf("%d %d %d\n",b[j][i],j,i);
            t++;j--;
        }
        if(t==N){break;}
        zuo++;i++;j++;
    }
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            printf("%d",b[i][j]);
            if(j!=n-1){
                printf(" ");
            }else{
                printf("\n");
            }
        }
    }
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324447701&siteId=291194637