PTA 乙级 1050 螺旋矩阵 (25分) C++
这题真的是想了老半天,也不太会,看了看别人的,学习学习
1 #include<iostream> 2 #include<algorithm> 3 #include<vector> 4 #include<cmath> 5 using namespace std; 6 /*用于排序的二维数组*/ 7 int out[10000][100] = { 0 }; 8 /*sort*/ 9 bool cmp(int a, int b) { 10 return a > b; 11 } 12 int main() { 13 int num = 0; 14 int n = 0, m = 0; 15 /*写入二维数组时的递增变量*/ 16 int a = 0; 17 /*四边形的每个边的层数*/ 18 int lel = 0; 19 cin >> num; 20 vector<int> arr(num); 21 for (int i = 0; i < num; ++i)cin >> arr[i]; 22 sort(arr.begin(), arr.end(), cmp); //输入数据从大到小排序 23 for (n = sqrt((double)num); n >= 1; n--) { //利用平方根寻找符合条件的m和n 24 if (num % n == 0) { 25 m = num / n; 26 break; 27 } 28 } 29 lel = m / 2 + m % 2; //长(正)方形边包含最多数字的个数(以最长的边为基准) 30 for (int i = 0; i < lel; ++i) { 31 for (int j = i; j < n - i && a < num; ++j)out[i][j] = arr[a++]; //上 32 for (int j = i + 1; j < m - i - 1 && a < num; ++j)out[j][n - i - 1] = arr[a++]; //右 33 for (int j = n - i - 1; j >= i && a < num; --j)out[m - i - 1][j] = arr[a++]; //下 34 for (int j = m - i - 2; j > i && a < num; --j)out[j][i] = arr[a++]; //左 35 } 36 for (int i = 0; i < m; ++i) { //输出 37 for (int j = 0; j < n; ++j) { 38 if (j == n - 1)cout << out[i][j]; 39 else cout << out[i][j] << ' '; 40 } 41 cout << endl; 42 } 43 return 0; 44 }
默默地一点点变强,细节决定成败