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 nsatisfy 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 1. 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>
using namespace std;
const int maxn = ; //数字不能太大
int matrix[maxn][maxn],A[maxn]; bool cmp(int a,int b){
return a > b;
} int main(){
int N;
scanf("%d",&N);
for(int i = ; i < N; i++){
scanf("%d",&A[i]);
}
if(N == ){
printf("%d",A[]);
return ;
}
sort(A,A+N,cmp);
int m = (int)ceil(sqrt(1.0*N));
while(N % m != ) m++; //除不整的时候m++
int n = N / m, i = , j = , now = ;
int U = , D = m, L = , R = n;
while(now < N){
while(now < N && j < R){
matrix[i][j] = A[now++];
j++;
}
while(now < N && i < D){
matrix[i][j] = A[now++];
i++;
}
while(now < N && j > L){
matrix[i][j] = A[now++];
j--;
}
while(now < N && i > U){
matrix[i][j] = A[now++];
i--;
}
U++,D--,L++,R--;
i++,j++;
if(now == N - ){
matrix[i][j] = A[now++];
}
}
for(int i = ; i <= m; i++){
for(int j = ; j <= n; j++){
printf("%d",matrix[i][j]);
if(j < n) printf(" "); //j < n,不是j < n - 1
else printf("\n");
}
}
return ;
}
最新文章
- Eclipse启动Tomcat时server.xml和content.xml自动还原问题
- 【Beta】Scrum03
- easyUI跨Tab操作datagrid
- 编程模式之观察者模式(Observer)
- HDOJ(1238) KMP
- python---hashlib
- quick cocos 的scheduler 定时器
- thinkphp文章列表及删除文章
- strstr strchr strrchr
- POJ 2411 Mondriaan&#39;sDream(状压DP)
- POJ 1743 后缀数组不重叠最长重复子串
- java隐士类型转换和强制类型转换
- 转载SSIS中的容器和数据流—数据转换(Transformations)
- 文成小盆友python-num9 socket编程
- 性能优化之Hibernate缓存讲解、应用和调优
- 08-C语言循环
- docker 设计原理
- MySQL慢查询日志配置方式 slow_query_log
- codeforces467C
- Codeforces 798D Mike and distribution