先这个博客的目的是提醒自己大数组初始化用memset或者fill,直接在定义的时候初始化很容易出问题。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4+10;
int N,n,dmin=1e9;
int arr[maxn];
int show[500][500];
bool cmp(int a, int b){
return a>b;
}
int main(){
scanf("%d", &N);
for(int i = 0; i<N; i++)
scanf("%d", &arr[i]);
memset(show, -1, sizeof(show));
sort(arr, arr+N, cmp);
for(int i = 1; i<=N; i++){
if(N%i == 0){
int m = N/i;
if(m < i) break;
if(m-i < dmin){
dmin = m-i;
n=i;
}
}
}
int m = N/n;
int st = 0,x=0,y=0;
while(st != N){
while(x>=0&&y>=0&&x<m&&y<n&&st<N&&show[x][y]==-1) show[x][y++]=arr[st++];
y--;x++;
while(x>=0&&y>=0&&x<m&&y<n&&st<N&&show[x][y]==-1) show[x++][y]=arr[st++];
x--;y--;
while(x>=0&&y>=0&&x<m&&y<n&&st<N&&show[x][y]==-1) show[x][y--]=arr[st++];
y++;x--;
while(x>=0&&y>=0&&x<m&&y<n&&st<N&&show[x][y]==-1) show[x--][y]=arr[st++];
x++;y++;
}
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
if(j != 0) printf(" ");
printf("%d", show[i][j]);
}
printf("\n");
}
return 0;
}