题目描述:
本题要求将给定的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
解题思路:
先排序,这个大家都知道,然后要注意的就是矩阵大小的选取,很重要!!!因为m >= n,m * n == N,N最大10000,所以n最多100,m可以达到9997,因此可以建立一个第一维度为10000,第二维度为100的数组。
代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 10005;
int a[maxn];
int b[10000][100];
int cmp(int a, int b) {
return a > b;
}
int main()
{
int N, n, m;
cin >> N;
for(int i = 0; i < N; i ++) {
cin >> a[i];
}
sort(a, a + N, cmp);
int d = 10000;
memset(b, 0, sizeof(b));
for(int i = 1; i * i <= N; i ++) {
if(N % i == 0) {
n = i;
m = N / i;
}
}
int tot = 0, x = 0, y = 0;
while(tot < N) {
while(y < n && !b[x][y]) {
b[x][y ++] = a[tot ++];
}
x += 1;
y --;
while(x < m && !b[x][y]) {
b[x ++][y] = a[tot ++];
}
x -= 1;
y --;
while(y >= 0 && !b[x][y]) {
b[x][y --] = a[tot ++];
}
x -= 1;
y += 1;
while(x >= 0 && !b[x][y]) {
b[x --][y] = a[tot ++];
}
x += 1;
y += 1;
}
for(int i = 0; i < m; i ++) {
for(int j = 0; j < n; j ++) {
if(j == 0)
cout << b[i][j];
else
cout << " " << b[i][j];
}
cout << endl;
}
return 0;
}