This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrixis filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and ncolumns, 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<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
int G[][];
int N, num[], index = ;
bool cmp(int a, int b){
return a > b;
}
int main(){
scanf("%d", &N);
for(int i = ; i < N; i++)
scanf("%d", &num[i]);
int sqr = sqrt(N * 1.0);
int m, n;
for(n = sqr; N % n != ; n--);
m = N / n;
sort(num, num + N, cmp);
int k = , j = , times = ;
while(index < N){
if(N - index == ){
G[k][j] = num[index];
break;
}
while(j < n - - times && index < N){
G[k][j++] = num[index++];
}
while(k < m - - times && index < N){
G[k++][j] = num[index++];
}
while(j > times && index < N){
G[k][j--] = num[index++];
}
while(k > times && index < N){
G[k--][j] = num[index++];
}
k++;
j++;
times++;
}
for(int i = ; i < m; i++){
for(int j = ; j < n; j++){
if(j == n - )
printf("%d", G[i][j]);
else
printf("%d ", G[i][j]);
}
printf("\n");
}
cin >> N;
return ;
}
总结:
1、采用旋转填充二维数组的方式的时候要注意,当遇到图形中心是一个时会出现死循环,需要特殊处理一下。如图:
2、测试数据:测试只有1个元素、只有1列元素、边长为奇数的正方形、边长偶数的正方形。
3、超时有可能是因为出现了死循环,而不一定是复杂度不对。
4、方法,设顶点为(x,y),边长为m、n。填充一圈后变为顶点(x+1, y+1),边长变为m - 2, n - 2。