题目描述
知识点: 模拟
思路: 蛇形数组模板题,开个方向数组模拟着填入就好。主要是求n,m。求最小乘积之差不能用sqrt,例如21。。还是老老实实模拟着算。
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e4+10;
int w,n,m,a[N],g[N][N];
int dx[] = {0,1,0,-1},dy[] = {1,0,-1,0};
int main(){
scanf("%d",&w);
for(int i = 0;i < w;i++) scanf("%d",&a[i]);
sort(a,a+w,greater<int>());
int n = 0,m = 0;
for(int i = 1;i <= w / i;i++){
if(w % i == 0){
n = w / i;
m = i;
}
}
int cnt = 0;
int x = 0,y = -1,guide = 0;
while(cnt < w){
int nx = x+dx[guide];
int ny = y+dy[guide];
if(nx < 0 || nx >= n || ny < 0 || ny >= m || g[nx][ny] != 0){
guide = (guide + 1)%4;
nx = x+dx[guide];
ny = y+dy[guide];
}
x = nx;
y = ny;
g[x][y] = a[cnt++];
}
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++)
{
if(j != m-1)
cout<<g[i][j]<<" ";
else cout<<g[i][j];
}
cout<<endl;
}
return 0;
}