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 93Sample Output:
98 95 93 42 37 81 53 20 76 58 60 76
将一个序列按正时针由外向内螺旋输出。由数组大小和题目的要求可以求出要输出的二维数组的长和宽,然后就能得到初始的上下左右端。先将序列从大到小排序,然后按照上上左右端把数组的数填入二维数组,然后更新上下左右端。最后输出二维数组即可。
代码:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int n;
cin>>n;
vector<int>a(n);
for(int i=0;i<n;i++) cin>>a[i];
sort(a.begin(),a.end(),greater<int>());
int w=sqrt(n);
while(n%w!=0) w--;
int h=n/w;
vector<vector<int> >b(h,vector<int>(w));
int l=0,r=w-1,u=0,d=h-1;
int idx=0;
while(l<r&&u<d)
{
for(int i=l;i<=r;i++) b[u][i]=a[idx++];
for(int i=u+1;i<=d;i++) b[i][r]=a[idx++];
for(int i=r-1;i>=l;i--) b[d][i]=a[idx++];
for(int i=d-1;i>=u+1;i--) b[i][l]=a[idx++];
l++;r--;
u++;d--;
}
if(l==r)
{
for(int i=u;i<=d;i++) b[i][l]=a[idx++];
}
else if(u==d)
{
for(int i=l;i<=r;i++) b[u][i]=a[idx++];
}
for(int i=0;i<h;i++)
{
cout<<b[i][0];
for(int j=1;j<w;j++)
{
cout<<" "<<b[i][j];
}
cout<<endl;
}
}