写起来感觉有点像推箱子游戏
#include <stdio.h>
#include <stdlib.h>
int cmp(const void* a,const void* b){
return *(int*)a - *(int*)b;
}
int main(){
int N,i,m,n,j;
int flag = 6;
static int a[10001],b[10000][100];//不是1w,测试点7会段错误,n<m所以一定小于100
scanf("%d",&N);
for(i = 1;i*i <= N;i++){
if(N % i == 0){
m = i;
n = N/m;
}
}
if(m < n){
i = m;
m = n;
n = i;
}
for(i = 0;i < N;i++){
scanf("%d",&a[i]);
}
qsort(a,N,sizeof(int),cmp);
i = j = 0;
//小游戏的移动
while(N){
b[i][j] = a[--N];
switch (flag){//对应数字键盘2↓,8↑,4←,6→
case 6:
if(j != n-1&&!b[i][j+1]){
j++;
break;
}
flag = 2;
case 2:
if(i != m-1&&!b[i+1][j]){
i++;
break;
}
flag = 4;
case 4:
if(j != 0&&!b[i][j-1]){
j--;
break;
}
flag = 8;
case 8:
if(!b[i-1][j]){
i--;
break;
}
flag = 6;
default:j++;break;
}
}
for(i = 0;i < m;i++){
for(j = 0;j < n;j++){
printf("%d",b[i][j]);
if(j != n-1){
printf(" ");
}else{
printf("\n");
}
}
}
}