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
关于螺旋矩阵的问题:可以一层一层的去解决,先将数组从大到小排序 设置矩阵的边界条件,上为u. 下为d 左为l 右为r 一层一层去填写, 一层填写完成后,u++ d-- l++ r-- . 最先要算出矩阵的规模 ,要求m行n列,m>=n m-n最小,那么m n都肯定是其因子, 故可求出数字的开方的上界, 往上++,直到N%m==0 此时m-n最小。注意只有一个元素时,直接输出。
#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include<vector>
#include<set>
#include<map>
#include<unordered_map>
#include<queue>
#include<algorithm>
#include<cmath>
using namespace std;
#define ll long long
#define vi vector<int>
#define pii pair<int, int>
#define x first
#define y second
const int maxn=11000;
bool cmp(int a,int b)
{
return a>b;
}
int mar[maxn][maxn],n,ans[maxn];
int main()
{
cin>>n;
for(int i=0;i<n;i++) cin>>ans[i];
if(n==1) {printf("%d",ans[0]); return 0;}
sort(ans,ans+n,cmp);
int m=(int)ceil(sqrt(1.0*n));
while(n%m!=0) m++;
int c=n/m, i=1,j=1,now=0;
int u=1,d=m,l=1,r=c;
while(now<n)
{
while(now<n&&j<r)
{
mar[i][j]=ans[now++];
j++;
}
while(now<n&&i<d)
{
mar[i][j]=ans[now++];
i++;
}
while(now<n&&j>l)
{
mar[i][j]=ans[now++];
j--;
}
while(now<n&&i>u)
{
mar[i][j]=ans[now++];
i--;
}
u++;d--;l++;r--;
i++;j++;
if(now==n-1)
{
mar[i][j]=ans[now++];
}
}
for(int i=1;i<=m;i++)
{
for(int j=1;j<=c;j++)
{
if(j<c) cout<<mar[i][j]<<" ";
else cout<<mar[i][j]<<endl;
}
}
return 0;
}