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 10​4​​. 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

题目大意:给你一组N个数据 a【】,让你螺旋式非递增填充矩阵,矩阵要求:行m>列n,且m与n的差值尽可能小。

分析:

1)要非递增填充,那就对数据sort递减排个序。

2)对于m、n的要求,对N开根且向上取整( ceil(num)可对num实现向上取整),找出第一个能整除N的m即可。

3)如何具体填充呢?

开四个变量U、D、L、R分别用作上下左右边界,然后遍历排好序的 a【】数组进行填充,每填充一圈U++,D--,L++,R--,i++,j++,直到只剩下一个元素位置时单独处理。

4)上述讨论都是基于至少螺旋一圈的情况,对于一组数据只有一个时应该进行特判输出。

完整代码:
 

#include<bits/stdc++.h>
using namespace std;
const int maxn=10010;
int matrix[maxn][maxn],a[maxn];

bool cmp(int a,int b){
	return a>b;
}

int main(){
	int N;
	cin>>N;
	for(int i=0;i<N;i++) cin>>a[i];
	if(N==1){
		cout<<a[0];
		return 0;
	} 
	sort(a,a+N,cmp);
	int m=(int)ceil(sqrt(N*1.0) );//ceil()用于向上取整 
	while(N%m!=0) m++; //找出最小行数 
	int n=N/m,i=1,j=1,cnt=0;
	int U=1,D=m,L=1,R=n; //四个边界 
	//开始螺旋式填充 
	while(cnt<N){
		while(cnt<N && j<R){ //向右填充 
			matrix[i][j++]=a[cnt++];
		}
		while(cnt<N && i<D){ //向下填充 
			matrix[i++][j]=a[cnt++];
		}
		while(cnt<N && j>L){//向左填充 
			matrix[i][j--]=a[cnt++];
		}
		while(cnt<N && i>U){ //向上填充 
			matrix[i--][j]=a[cnt++];
		}
		U++,D--,L++,R--;
		i++,j++;
		if(cnt==N-1) matrix[i][j]=a[cnt++]; 
	}
	for(int i=1;i<=m;i++){
		for(int j=1;j<=n;j++){
			printf("%d%s",matrix[i][j],j<n? " ":"\n");
		}
	}
	return 0;
} 

That’s all !

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZCAIHUI_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值