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
#include<bits/stdc++.h>
using namespace std;
bool cmp(int a, int b){
return a > b;
}
int main(){
int N, num[10010];
scanf("%d", &N);
for(int i = 0; i < N; i++)
scanf("%d", &num[i]);
sort(num, num + N, cmp);
int m, n;
m = sqrt(N);
if(N / m != m)
m=m+1;
for(int i = m; i <= N; i++)
if(N % i == 0){
m = i;
break;
}
n = N / m;
/* if(n == 1){
for(int i = 0; i < m; i++)
printf("%d\n", num[i]);
return 0;
}*/
int left = 0, right = n, up = 1, down = m;
int matrix[110][110], sum = 0;
while(sum < N){
int i, j;
i = j = left;
while(j < right){
matrix[i][j++] = num[sum++];
}
if(sum == N)
break;
j--;
i++;
while(i < down){
matrix[i++][j] = num[sum++];
}
if(sum == N)
break;
i--;
j--;
while(j >= left){
matrix[i][j--] = num[sum++];
}
if(sum == N)
break;
j++;
i--;
while(i >= up){
matrix[i--][j] = num[sum++];
}
if(sum == N)
break;
left++;
right--;
up++;
down--;
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(j != n-1)
printf("%d ", matrix[i][j]);
else
printf("%d\n", matrix[i][j]);
}
}
return 0;
}