标签:25 matrix int Spiral spiral 1105 numbers each line
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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。