复习总结提高版
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define not !
#define and &&
#define or ||
#define ri register int
#define rep(inc, frm, to) for (ri inc = frm; inc < (to); ++inc)
#define rep2(inc, frm, to) for (ri inc = frm; inc > (to); --inc)
#define MAX_N 10010
int n, M, N, nums[MAX_N];
int cmp(const void* e1, const void* e2) {
return *(int*) e2 - *(int*) e1;
}
void print_arr(int arr[], const size_t sz) {
rep(i, 0, sz) printf("%d%c", *(arr + i), i == sz - 1 ? 10 : 32);
}
signed main(int argc, char const *argv[]) {
scanf("%d", &n);
rep(i, 0, n) scanf("%d", nums + i);
qsort(nums, n, sizeof(int), cmp);
for (ri i = sqrt(n); i; --i)
if (not(n % i)) {
M = n / i, N = i;
break;
}
int matrix[M][N];
int top = 0, bottom = M - 1, left = 0, right = N - 1, dir = 0, cnt = 0;
while (top <= bottom and left <= right) {
switch (dir) {
case 0: // 由左至右
for (ri x = left; x <= right; ++x)
*(*(matrix + top) + x) = *(nums + cnt++);
++top;
break;
case 1:
for (ri y = top; y <= bottom; ++y)
*(*(matrix + y) + right) = *(nums + cnt++);
--right;
break;
case 2:
for (ri x = right; x >= left; --x)
*(*(matrix + bottom) + x) = *(nums + cnt++);
--bottom;
break;
case 3:
for (ri y = bottom; y >= top; --y)
*(*(matrix + y) + left) = *(nums + cnt++);
++left;
break;
default:
puts("something is wrong!!!");
break;
}
dir = (dir + 1) % 4;
}
rep(y, 0, M) rep(x, 0, N)
printf("%d%c", *(*(matrix + y) + x), x == N - 1 ? 10 : 32);
return ~~(0 ^ 0);
}
模拟!
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
int n, M, N;
int main(void) {
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; ++i) cin >> nums[i];
sort(rbegin(nums), rend(nums));
for (int i = sqrt(n); i >= 1; --i) { // 试除法
if (!(n % i)) {
M = n / i;
N = i;
break;
}
}
int idx = 0, dir = 0,
left = 0, right = N - 1,
top = 0, bottom = M - 1;
vector<vector<int>> matrix(M, vector<int>(N));
while (left <= right and top <= bottom) {
switch (dir) {
case 0:
for (int x = left; x <= right; ++x)
matrix[top][x] = nums[idx++];
++top;
break;
case 1:
for (int y = top; y <= bottom; ++y)
matrix[y][right] = nums[idx++];
--right;
break;
case 2:
for (int x = right; x >= left; --x)
matrix[bottom][x] = nums[idx++];
--bottom;
break;
case 3:
for (int y = bottom; y >= top; --y)
matrix[y][left] = nums[idx++];
++left;
break;
}
dir = (dir + 1) % 4;
}
for (const auto& r : matrix) {
for (int i = 0; i < r.size(); ++i) {
printf("%d", r[i]);
if (i < r.size() - 1) putchar(' ');
}
putchar('\n');
}
}