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; m≥n; and m−n 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
就是一个分块思想
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;//使用数据的下角标 21 while (lm <= rm && ln <= rn && k < nn) 22 { 23 if (lm == rm)//只有一行,则打印 24 for (int i = ln; i <= rn; ++i) 25 arry[lm][i] = v[k++]; 26 else if (ln == rn)//只有一列 27 for (int i = lm; i <= rm; ++i) 28 arry[i][ln] = v[k++]; 29 else 30 { 31 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++;//左上角右下移 41 rm--, rn--;//右下角左上移 42 } 43 for (int i = 0; i < m; ++i) 44 { 45 for (int j = 0; j < n; ++j) 46 cout << arry[i][j] << (j == n - 1 ? "" : " "); 47 cout << endl; 48 } 49 return 0; 50 }