本题要求将给定的 N 个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第 1 个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为 m 行 n 列,满足条件:m×n 等于 N;m≥n;且 m−n 取所有可能值中的最小值。
输入格式:
输入在第 1 行中给出一个正整数 N,第 2 行给出 N 个待填充的正整数。所有数字不超过 104,相邻数字以空格分隔。
输出格式:
输出螺旋矩阵。每行 n 个数字,共 m 行。相邻数字以 1 个空格分隔,行末不得有多余空格。
输入样例:
12
37 76 20 98 76 42 53 95 60 81 58 93
结尾无空行
输出样例:
98 95 93
42 37 81
53 20 76
58 60 76
结尾无空行
题目分析
反正
哎
反正。。
算了
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> bag;
vector<vector<int>> matrix;
int N;
int m, n;
cin >> N;
for (m = sqrt(N); m < N; m++)
{ // m = row,n = col;
if (!(N % m)) {
break;
}
}
m = max(m, N / m);
n = N / m;
// get n,m;
int temp;
for (int i = 0; i < N; i++) {
cin >> temp;
bag.push_back(temp);
}
sort(bag.rbegin(), bag.rend());//sort
// fill in
matrix.resize(m, vector<int>(n));
int cnt = 0;
int i = 0, j = 0;
while (cnt < m * n - 1) {
while (j < n - 1 && matrix[i][j + 1] == 0) {
matrix[i][j++] = bag[cnt++];
}
while (i < m - 1 && matrix[i + 1][j] == 0) {
matrix[i++][j] = bag[cnt++];
}
while (j > 0 && matrix[i][j - 1] == 0) {
matrix[i][j--] = bag[cnt++];
}
while (i > 0 && matrix[i - 1][j] == 0) {
matrix[i--][j] = bag[cnt++];
}
}
matrix[i][j] = bag[bag.size()-1];
for (int i = 0; i < matrix.size();i++) {
for (int j = 0; j < n;j++) {
if (j != 0)cout << ' ';
cout << matrix[i][j];
}
if (i != m - 1) {
cout << endl;
}
}
}