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 nsatisfy 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
题目大意:给你一组N个数据 a【】,让你螺旋式非递增填充矩阵,矩阵要求:行m>列n,且m与n的差值尽可能小。
分析:
1)要非递增填充,那就对数据sort递减排个序。
2)对于m、n的要求,对N开根且向上取整( ceil(num)可对num实现向上取整),找出第一个能整除N的m即可。
3)如何具体填充呢?
开四个变量U、D、L、R分别用作上下左右边界,然后遍历排好序的 a【】数组进行填充,每填充一圈U++,D--,L++,R--,i++,j++,直到只剩下一个元素位置时单独处理。
4)上述讨论都是基于至少螺旋一圈的情况,对于一组数据只有一个时应该进行特判输出。
完整代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=10010;
int matrix[maxn][maxn],a[maxn];
bool cmp(int a,int b){
return a>b;
}
int main(){
int N;
cin>>N;
for(int i=0;i<N;i++) cin>>a[i];
if(N==1){
cout<<a[0];
return 0;
}
sort(a,a+N,cmp);
int m=(int)ceil(sqrt(N*1.0) );//ceil()用于向上取整
while(N%m!=0) m++; //找出最小行数
int n=N/m,i=1,j=1,cnt=0;
int U=1,D=m,L=1,R=n; //四个边界
//开始螺旋式填充
while(cnt<N){
while(cnt<N && j<R){ //向右填充
matrix[i][j++]=a[cnt++];
}
while(cnt<N && i<D){ //向下填充
matrix[i++][j]=a[cnt++];
}
while(cnt<N && j>L){//向左填充
matrix[i][j--]=a[cnt++];
}
while(cnt<N && i>U){ //向上填充
matrix[i--][j]=a[cnt++];
}
U++,D--,L++,R--;
i++,j++;
if(cnt==N-1) matrix[i][j]=a[cnt++];
}
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
printf("%d%s",matrix[i][j],j<n? " ":"\n");
}
}
return 0;
}
That’s all !