1050 螺旋矩阵(25 分)

本题要求将给定的 N 个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第 1 个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为 m 行 n 列,满足条件:m×n 等于 N;m≥n;且 m−n 取所有可能值中的最小值。

输入格式:

输入在第 1 行中给出一个正整数 N,第 2 行给出 N 个待填充的正整数。所有数字不超过 10​4​​,相邻数字以空格分隔。

输出格式:

输出螺旋矩阵。每行 n 个数字,共 m 行。相邻数字以 1 个空格分隔,行末不得有多余空格。

输入样例:

12
37 76 20 98 76 42 53 95 60 81 58 93

输出样例:

98 95 93
42 37 81
53 20 76
58 60 76
#include<iostream>
#include<algorithm>
#include<math.h>//有sqrt要加math
using namespace std;

bool gr(int a,int b){
	return a>b;
}
int b[10010][110];//数组过大,在main里面会报错,只能定义为全局变量,醉。。。
int a[10010];
int main(){	
	while(1){
		int n;
		scanf("%d",&n);		
		for(int i=0;i<n;++i)
			scanf("%d",&a[i]);		
		sort(a,a+n,gr);
		int m,l,n0=sqrt((double)n);
		for(int i=n0;i>0;--i){
			if(n%i==0){
				l=i;
				break;
			}
		}
		m=n/l;
		if(l>m){
			swap(m,l);
		}
		//cout<<"m="<<m<<"  l="<<l<<endl;


		for(int i=0;i<10010;++i){
			for(int j=0;j<110;++j)
				b[i][j]=0;
		}

		int x=0;
		int qh=0,ql=0;
		while(x<n){				
				while(ql<l&&b[qh][ql]==0)//b[qh][ql]==0这个判断条件很核心
					b[qh][ql++]=a[x++];
				++qh;
				--ql;
				//cout<<"qh="<<qh<<"  ql="<<ql<<endl;
				while(qh<m&&b[qh][ql]==0)
					b[qh++][ql]=a[x++];	
				--qh;
				--ql;
				//cout<<"qh="<<qh<<"  ql="<<ql<<endl;
				while(ql>=0&&b[qh][ql]==0)
					b[qh][ql--]=a[x++];				
				++ql;
				--qh;
				//cout<<"qh="<<qh<<"  ql="<<ql<<endl;
				while(qh>=0&&b[qh][ql]==0)
					b[qh--][ql]=a[x++];				
				++qh;
				++ql;
				//cout<<"qh="<<qh<<"  ql="<<ql<<endl;
		}

		for(int i=0;i<m;++i){
			cout<<b[i][0];
			for(int j=1;j<l;++j){
				cout<<" "<<b[i][j];
			}
			cout<<endl;
		}

	}
}

猜你喜欢

转载自blog.csdn.net/qq_31647835/article/details/82218358