1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
| #include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
bool cmp(int a, int b){
return a > b;
}
int main(){
int N;
cin >> N;
vector<int >A(N);
for (int i = 0; i < N; i++){
cin >> A[i];
}
if (N == 1){
cout << A[0];
return 0;
}
sort(A.begin(), A.end(), cmp);
//int m = sqrt(N);//这样写不行,需要取不小于sqrt(N)的整数
int m = (int)ceil(sqrt(1.0*N));//ceil向上取整,不小于这个数的整数
while (N%m != 0){
m++;
}
int n = N / m,i=0,j=0,now=0;
int U = 0, D = m-1, L = 0, R = n-1;
vector<vector<int> > matrix(m, vector<int>(n));//定义二维的数组.只不过这是动态的.
//用静态数组预先分配空间会出现内存超限...
//问题是,同一道题,同样的解法,放在甲级里提交就AC,乙级就内存超限~~
//所以,不预先分配空间了,使用动态的了~~
while (now < N){
while (now <N&&j < R){//右
matrix[i][j] = A[now++];
j++;
}
while (now < N&&i < D){//下
matrix[i][j] = A[now++];
i++;
}
while (now < N&&j > L){//左
matrix[i][j] = A[now++];
j--;
}
while (now < N&&i > U){//上
matrix[i][j] = A[now++];
i--;
}
U++, D--, L++, R--;
i++, j++;
if (now == N - 1){//如果最里层只有一个数需要特殊处理.
matrix[i][j] = A[now++];
}
}
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
cout << matrix[i][j];
if (j != n-1) cout << " ";
else cout << endl;
}
}
return 0;
}
|