您的位置:首页 > 其它

1105. Spiral Matrix (25)

2018-02-18 16:44 393 查看

1105. Spiral Matrix (25)

时间限制150 ms
内存限制65536 kB
代码长度限制16000 B
判题程序Standard作者CHEN, Yue
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<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int main(){
int N,i,j;
scanf("%d",&N);
int a
;
for(i=0;i<N;i++){
scanf("%d",&a[i]);
}
sort(a,a+N,cmp);
int m,n;
//	m=(int)ceil(sqrt(1.0*N));
//	while(N%m!=0){
//		m++;
//	}
n=sqrt(N);
while(N%n){
n--;
}
m=N/n;
int b[m]
;
//	int b[m]
={0};  貌似这样不能给 数组全部赋初值为 0...
fill(b[0],b[0]+m*n,0);
int cou=0;
i=0,j=0;
while(cou!=N){
for(;j<n&&b[i][j]==0;j++){
b[i][j]=a[cou++];
}
j--;
i++;
for(;i<m&&b[i][j]==0;i++){
b[i][j]=a[cou++];
}
i--;
j--;
for(;j>=0&&b[i][j]==0;j--){
b[i][j]=a[cou++];
}
i--;
j++;
for(;i>=0&&b[i][j]==0;i--){
b[i][j]=a[cou++];
}
i++;
j++;
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d",b[i][j]);
if(j!=n-1){
printf(" ");
}
else{
printf("\n");
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: