其实模拟题是最难的,没有所谓的模版而言。这里我写的边界条件不是很清晰,是因为后来发现有bug慢慢补的。总体思想就是排序后,从0, m - 1开始。第一个是左到右x轴++,然后第二个是y--,第三个是x--,第四个是y++;
每一个自增自减都要判断边界条件,是否超过m * n的矩形,是否已经有数据了,是否到头了。
#include<bits/stdc++.h>
using namespace std;
int n, N, M, pos = 0;
vector<int> v;
vector<vector<int>> ans;
bool cmp (int a, int b) {
return a > b;
}
void sp1 (int &x, int &y) {
while (x < N && ans[x][y] == 0 && pos < n) {
ans[x][y] = v[pos++];
if (x + 1 < N && ans[x + 1][y] == 0) x++;
else break;
}
if (y - 1 >= 0) y--;
}
void sp2 (int &x, int &y) {
while (y >= 0 && ans[x][y] == 0 && pos < n) {
ans[x][y] = v[pos++];
if (y - 1 >= 0 && ans[x][y - 1] == 0) y--;
else break;
}
if (x - 1 >= 0) x--;
}
void sp3 (int &x, int &y) {
while (x >= 0 && ans[x][y] == 0 && pos < n) {
ans[x][y] = v[pos++];
if (x - 1 >= 0 && ans[x - 1][y] == 0) x--;
else break;
}
if (y + 1 < M) y++;
}
void sp4 (int &x, int &y) {
while (y < M && ans[x][y] == 0 && pos < n) {
ans[x][y] = v[pos++];
if (y + 1 < M && ans[x][y + 1] == 0) y++;
else break;
}
if (x + 1 < N) x++;
}
int main() {
scanf ("%d", &n);
v.resize(n);
for (int i = 0; i < n; i++) scanf ("%d", &v[i]);
for (int i = 1; i <= n; i++) {
int m = n / i;
if (m * i == n && m >= i) {
M = m;
N = i;
}
else if (i > m) break;
}
// cout << M << ' ' << N << endl;
ans.resize(N);
for (int i = 0; i < N; i++) ans[i].resize(M);
sort (v.begin(), v.end(), cmp);
int x = 0, y = M - 1;
for (int i = 0; i < n; i++) {
if (pos == n) break;
sp1(x, y);
sp2(x, y);
sp3(x, y);
sp4(x, y);
}
for (int i = M - 1; i >= 0; i--) // y轴
{
for (int j = 0; j < N; j++) {
if (j != 0) printf (" ");
printf ("%d", ans[j][i]);
}
printf ("\n");
}
}