很早之前的写法···
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,k;
int a[150][150],b[10010];
void dfs()
{
int p = 1;int i =1,j=1;a[1][1]=b[k-p+1];
while(p<n*m){
if(!a[i][j+1]&&(a[i-1][j]&&a[i][j-1]||j<n&&i==1||j<n&&a[i-1][j]))
a[i][++j]=b[k-++p + 1];
else if(!a[i+1][j]&&(a[i][j+1]&&a[i-1][j]&&a[i+1][j]||i<m))
a[++i][j]=b[k - ++p + 1];
else if(!a[i][j-1]&&(j>1||a[i][j+1]&&a[i+1][j]&&a[i-1][j]))
a[i][--j]=b[k - ++p + 1];
else
a[--i][j]=b[k - ++p + 1];
}
}
int main()
{
scanf("%d",&k);
for(int i = 1;i <= sqrt(k);i ++)
if(k % i == 0)
m = i;
n = k / m;
if(m < n)
swap(m,n);
for(int i = 1;i <= k;i ++)
scanf("%d",&b[i]);
sort(b + 1,b + 1 + k);
dfs();
for(int i = 1;i<=m;i++){
for(int j = 1;j<=n;j++){
printf("%d ",a[i][j]);
}printf("\n");
}
return 0;
}
借鉴y总的写法
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,k;
int a[150][150],b[10010];
void dfs()
{
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int x = 1, y = 1,d = 1;
for (int i = 1; i <= k; i ++ )
{
a[x][y] = b[i];
int xx = x + dx[d], yy = y + dy[d];
if (xx < 1 || xx > m || yy < 1 || yy > n || a[xx][yy])
{
d = (d + 1) % 4;
xx = x + dx[d], yy = y + dy[d];
}
x = xx, y = yy;
}
}
int main()
{
scanf("%d",&k);
for(int i = 1;i <= sqrt(k);i ++)
if(k % i == 0)
m = i;
n = k / m;
if(m < n)
swap(m,n);
for(int i = 1;i <= k;i ++)
scanf("%d",&b[i]);
sort(b + 1,b + 1 + k);
reverse(b + 1,b + 1 + k);
dfs();
for(int i = 1;i<=m;i++){
cout<<a[i][1];
for(int j = 2;j<=n;j++){
printf(" %d",a[i][j]);
}printf("\n");
}
return 0;
}