PAT Grade --A1105 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; mn; and mn 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 Npositive integers to be filled into the spiral matrix. All the numbers are no more than 1. 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

Is a block thought
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #include <cmath>
 5 using namespace std;
 6 int nn, m, n;
 7 int main()
 8 {
 9     cin >> nn;
10     vector<int>v(nn);
11     for (int i = 0; i < nn; ++i)
12         cin >> v[i];
13     n = floor(sqrt(nn));//取小值
14     while (nn%n!=0)n--;//找到m,n
15     m = nn / n;
16     vector<vector<int>>arry(m, vector<int>(n, 0));    
17     sort(v.begin(), v.end(), [](int a, int b) {return a > b; });
18     int lm = 0, ln = 0;//左上角
19     int rm = m - 1, rn = n - 1;//右下角
20     int k = 0 ; // use the suffix data 
21 is      the while (LM <= RM && LN <= K RN && < NN)
 22 is      {
 23 is          IF (LM == RM) // only one line is printed 
24              for ( int I = LN ; I <= RN; ++ I)
 25                  ARRY [LM] [I] = V [K ++ ];
 26 is          the else  IF (LN == RN) // only one column 
27              for ( int I = LM; I <= RM; ++ I)
 28                  ARRY [I] [LN] = V [K ++ ];
 29          the else 
30          {
 31 is             for (int i = ln; i < rn; ++i)//上行
32                 arry[lm][i] = v[k++];
33             for(int i=lm;i<rm;++i)//右列
34                 arry[i][rn]= v[k++];
35             for (int i = rn; i > ln; --i)//下行
36                 arry[rm][i] = v[k++];
37             for (int i = rm; i > lm; --i)
38                 arry[i][ln] = v[k++];
39         }
40         ++ LM, LN ++; // the top left and right down 
41 is          rm--, rn--; // lower right corner of the upper left shifter 
42 is      }
 43 is      for ( int I = 0 ; I <m; ++ I)
 44 is      {
 45          for ( int = J 0 ; J <n-; ++ J)
 46 is              COUT << ARRY [I] [J] << (n-J == - . 1 ? "" : "  " );
 47          COUT << endl;
 48      }
 49      return  0 ;
 50 }

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/11441585.html