原题链接: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
题目大意: 给出一堆数,让你按照非递增的排序以顺时针螺旋的方式将这些数排列打印。
分析:
- 将这些数读入,然后用sort排序;
- 计算出m和n。因为m和n的乘积是N,并且m比n略大。那么从sqrt(N)开始往下找,第一个能被N整除的就是n,拿N除一下就能得到m;
- 接下来就是最关键的打表部分了,可以参考柳神的博客,写的很详细。首先先计算出这个螺旋排列有多少层:m为偶数时,level为m/2;m为奇数时level为m/2+1。因此
level = m/2 + m%2
。接着外层循环控制着从0到level-1,内层是四个for,按照左上到右上、右上到右下、右下到左下,左下到右上的顺序填入矩阵b[m][n];(注意要控制t <= N - 1
,因为当所有数都填完了就不继续往里填了) - 打印矩阵
int b[m][n];
int level = m / 2 + m % 2; //level层数
for(int i = 0; i < level; i++){
for(int j = i; j <= n - 1 - i && t <= N - 1; j++) //左上到右上
b[i][j] = a[t++];
for(int j = i + 1; j <= m - 2 - i && t <= N - 1; j++) //右上到右下
b[j][n - 1 - i] = a[t++];
for(int j = n - i - 1; j >= i && t <= N - 1; j--) //右下到左下
b[m - 1 - i][j] = a[t++];
for(int j = m - 2 - i; j >= i + 1 && t <= N - 1; j--) //左下到左上
b[j][i] = a[t++];
}
代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
bool cmp1(int a, int b){
return a > b;
}
int main(){
int N, n, m, t = 0; //t相当于编号
cin >> N;
vector<int> a(N);
for(int i = 0; i < N; i ++ ){
cin >> a[i];
}
sort(a.begin(), a.end(), cmp1); //按非递增排序
for (int i = sqrt(N); i >= 1; i--) { //找到n和m
if (N % i == 0) {
m = N / i;
n = i;
break;
}
}
int b[m][n]; //按螺旋填入矩阵
int level = m / 2 + m % 2; //level层数
for(int i = 0; i < level; i++){
for(int j = i; j <= n - 1 - i && t <= N - 1; j++) //左上到右上
b[i][j] = a[t++];
for(int j = i + 1; j <= m - 2 - i && t <= N - 1; j++) //右上到右下
b[j][n - 1 - i] = a[t++];
for(int j = n - i - 1; j >= i && t <= N - 1; j--) //右下到左下
b[m - 1 - i][j] = a[t++];
for(int j = m - 2 - i; j >= i + 1 && t <= N - 1; j--) //左下到左上
b[j][i] = a[t++];
}
for(int i = 0; i < m; i ++ ){ //打印矩阵
for(int j = 0; j < n; j ++ ){
printf("%d", b[i][j]);
if(j != n-1) printf(" ");
else printf("\n");
}
}
return 0;
}