1105 Spiral Matrix(25 分)
This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrix is filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and n columns, where m and n satisfy the following: m×n must be equal to N; m≥n; and m−n is the minimum of all the possible values.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains N positive integers to be filled into the spiral matrix. All the numbers are no more than 104. The numbers in a line are separated by spaces.
Output Specification:
For each test case, output the resulting matrix in m lines, each contains n numbers. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.
Sample Input:
12
37 76 20 98 76 42 53 95 60 81 58 93
Sample Output:
98 95 93
42 37 81
53 20 76
58 60 76
怎么写一个 可以打印矩形 好看又整洁的代码 这么难。
code
#pragma warning(disable:4996)
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
vector<int> varr;
int map[200][200];
int idex = 0;
int deal(int n);
void printmatrix(int row, int col);
bool cmp(const int& a, const int& b);
int main() {
int n, x;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> x;
varr.push_back(x);
}
sort(varr.begin(), varr.end(), cmp);
int col = deal(n), row = n / col;
printmatrix(row, col);
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (j != 0) cout << ' ';
cout << map[i][j];
}
cout << endl;
}
system("pause");
return 0;
}
bool cmp(const int& a, const int& b) {
return a > b;
}
int deal(int n) {
int i;
for (i = sqrt(n); i > 0; --i) {
if (n%i == 0) break;
}
return i;
}
void printmatrix(int m, int n) {
int x = 0, y = 0;
while (1) {
int i = x, j = y;
if (idex == varr.size() - 1) {
map[i][j] = varr[idex++];
return;
}
while (j+1 < n) {
map[i][j] = varr[idex++];
++j;
if (idex == varr.size()) return;
}
while (i+1 < m) {
map[i][j] = varr[idex++];
++i;
if (idex == varr.size()) return;
}
while (j-1 >= y) {
map[i][j] = varr[idex++];
--j;
if (idex == varr.size()) return;
}
while (i-1 >= x) {
map[i][j] = varr[idex++];
--i;
if (idex == varr.size()) return;
}
x++;
y++;
m--;
n--;
}
}