题目

12
37 76 20 98 76 42 53 95 60 81 58 93

98 95 93
42 37 81
53 20 76
58 60 76

分析

1.先按倒序排列数组：

2.根据输入的数组个数，求出矩阵的行数和列数：

3.螺旋放置：

源代码

//C/C++实现
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

bool compare(int a, int b){
return a > b; //desc
}

int main(){
int N;
scanf("%d", &N);
vector<int> v(N);
for(int i = 0; i < N; ++i){
scanf("%d", &v[i]);
}
//sort
sort(v.begin(), v.end(), compare);
//calculate m and n
int i = sqrt((double)N);
int m, n;
for(; i >= 1; --i){
if(N % i == 0){ //整除
n = i;
m = N / n;
break;
}
}
int a[m][n]; //一会改成a[m][n]
int x = 0, y = -1;
int status = 0; //从左向右是0，上向下是1，右向左是2，下向上是3
int c0 = 0, c1 = 0, c2 = 0, c3 = 0; //走过该路径就自增1
if(n == 1){
for(int i = 0; i < v.size(); ++i){
printf("%d\n", v[i]);
}
}
else{
for(int i = 0; i < v.size(); ++i){
if(status == 0){
++y;
if(y == n - 1 - c1){
status = 1; //该从上往下填充了
++c0;
}
}
else if(status == 1){
++x;
if(x == m - 1 - c2){
status = 2; //该从右往左填充了
++c1;
}
}
else if(status == 2){
--y;
if(y == 0 + c3){
status = 3; //该从下往上填充了
++c2;
}
}
else if(status == 3){
--x;
if(x == 0 + c0){ //该从左往右填充了
status = 0;
++c3;
}
}
a[x][y] = v[i];
}
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(j == 0){
printf("%d", a[i][j]);
}
else{
printf(" %d", a[i][j]);
}
}
printf("\n");
}
}
return 0;
}