您的位置:首页 > 其它

1105. Spiral Matrix (25)

2017-07-31 10:00 351 查看
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


找规律

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<stack>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int main(){
int N;
cin>>N;
int a[10001];
for(int i=0;i<N;i++) scanf("%d",&a[i]);
sort(a,a+N,cmp);
int n,m;
int min=10000;
int h=0,l=0;
for(n=1;n<=N;n++){
for(m=n;n*m<=N;m++){
if(n*m==N&&m-n<min){
min=m-n;
h=m,l=n;
}
}
}
static int out[1000][1000];
int sum=0;
int shang=0,xia=h-1,zuo=0,you=l-1;
while(sum!=N){
for(int i=zuo;i<=you;i++){
out[shang][i]=a[sum++];
// cout<<out[shang][i]<<" ";
}
if(sum==N) break;
shang++;
for(int i=shang;i<=xia;i++){
out[i][you]=a[sum++];
// cout<<out[you][i]<<" ";
}
if(sum==N) break;
you--;
for(int i=you;i>=zuo;i--){
out[xia][i]=a[sum++];
// cout<<out[xia][i]<<" ";
}
if(sum==N) break;
xia--;
for(int i=xia;i>=shang;i--){
out[i][zuo]=a[sum++];
// cout<<out[zuo][i]<<" ";
}
if(sum==N) break;
zuo++;
}
for(int i=0;i<h;i++){
for(int j=0;j<l;j++)
if(j==l-1) cout<<out[i][j];
else
cout<<out[i][j]<<" ";
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: