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<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
bool cmp(int a, int b){
return a > b;
}
int main(){
int a[10001];
int n;
cin >> n;
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
sort(a, a + n, cmp);
int sqrt_n = sqrt(n);
int flag;
for(int i = 1; i <= sqrt_n; i++){
if(n % i == 0){
flag = i;
}
}
int m = n / flag;
int l = 1;
int r = flag;
int up = 2;
int down = m;
int temp_row = 1;
int temp_column = 1;
int order = 1;
int b[1000][1000];
for(int i = 0; i < n; i++){
b[temp_row][temp_column] = a[i];
if(order == 1){
if(temp_column < r){
temp_column++;
}else{
order = 2;
r--;
}
}
if(order == 2){
if(temp_row < down)
{
temp_row++;
}else
{
order = 3;
down--;
}
}
if(order == 3){
if(temp_column > l){
temp_column--;
}else
{
order = 4;
l++;
}
}
if(order == 4){
temp_row--;
if(temp_row == up){
order = 1;
up++;
}
}
}
for(int i = 1; i <= m; i++){
for(int j = 1; j <= flag; j++){
printf("%d%s", b[i][j], j != flag ? " " : "\n");
}
}
return 0;
}
zbchenchanghao 发布了65 篇原创文章 · 获赞 4 · 访问量 890 私信 关注
标签:25,matrix,int,Spiral,spiral,1105,numbers,each,line 来源: https://blog.csdn.net/zbchenchanghao/article/details/104161098