1050 螺旋矩阵 (25 分)

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

输入格式:

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

输出格式:

输出螺旋矩阵。每行 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<string>
using namespace std;
#include<math.h>
#include<algorithm>
int arr[1000000];
int shuchu[10000][10000];
int cmp(int a, int b);
int main() {
	int N;
	cin >> N;
	int m, n;
	for (int cnt = 0; cnt < N; cnt++) {
		cin >> arr[cnt];
	}
	sort(arr, arr + N,cmp);
	for (int cnt = sqrt((double)N); cnt >= 1; cnt--) {
		if (N % cnt == 0) {
			n = cnt;
			m = N / cnt;
			break;
		}
	}

	int i = 0;
	for (int cnt = 0; cnt < m / 2 + m % 2; cnt++) {
		for (int cnt1 = cnt; cnt1 < n - cnt && i<N; cnt1++) 
			shuchu[cnt][cnt1] = arr[i++];
		for (int cnt1 = cnt+1; cnt1 < m - 1 - cnt && i < N  ; cnt1++)
			shuchu[cnt1][n - 1 - cnt] = arr[i++];
		for (int cnt1 = n - 1 - cnt; cnt1 >= cnt && i < N; cnt1--)
			shuchu[m - 1 - cnt][cnt1] = arr[i++];
		for (int cnt1 = m-2-cnt; cnt1 >=cnt+1 && i < N  ; cnt1--)
			shuchu[cnt1][cnt] = arr[i++];
	}


	for (int cnt = 0; cnt < m; cnt++) {
		for (int cnt1 = 0; cnt1 < n; cnt1++) {
			printf("%d",shuchu[cnt][cnt1]);
			if (cnt1 != n - 1)printf(" ");
		}
		cout << endl;
	}

	return 0;

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

我踩过的坑,这题如果出现了格式错误,注意下是不是行列反了,还有个特征就是,两个格式错误,一个答案错误,基本就是行列搞混了导致的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

cjz-lxg

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

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

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

打赏作者

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

抵扣说明:

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

余额充值