题目链接:
https://pintia.cn/problem-sets/994805342720868352/problems/994805363117768704
思路:
1.将所给序列倒序排序;
2.一圈一圈地将序列逆时针填入矩阵;我的思路是使用变量x,y来表示当前我们所需操作的矩阵位置,然后按如下顺序挨个填入数据;
重点是对x,y坐标位置的控制;
代码:
#include <bits/stdc++.h>using namespace std;int N, m, n;int main() {
#ifdef MyTestfreopen("Sakura.txt", "r", stdin);
#endifscanf("%d", &N);vector<int> arr(N);for(int i = 0; i < N; ++i) scanf("%d", &arr[i]);sort(arr.begin(), arr.end(), greater<int>());n = sqrt(N);while(N % n) --n;m = N / n;vector<vector<int> > mat(m, vector<int>(n));int mm = m, nn = n, pos = 0, x = 0, y = 0;while(pos < N) {for(int i = 0; i < nn; ++i) mat[x][y++] = arr[pos++];--y, ++x;if(pos >= N) break;for(int i = 0; i < mm - 2; ++i) mat[x++][y] = arr[pos++];if(pos >= N) break;for(int i = 0; i < nn; ++i) mat[x][y--] = arr[pos++];if(pos >= N) break;++y, --x;for(int i = 0; i < mm - 2; ++i) mat[x--][y] = arr[pos++];++x, ++y;mm -= 2;nn -= 2;}for(int i = 0; i < m; ++i) {for(int j = 0; j < n; ++j) {if(j) putchar(' ');printf("%d", mat[i][j]);}putchar('\n');}return 0;
}