PAT (Advanced Level) Practise 1105 Spiral Matrix (25)

本文介绍了一种算法,该算法能够将一系列正整数按非递增顺序填充到螺旋矩阵中。螺旋矩阵的行列数需满足特定条件:行列乘积等于元素总数,行数大于等于列数,且行列数之差尽可能小。文章提供了输入输出规范及示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1105. Spiral Matrix (25)

时间限制
150 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 ncolumns, 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

题意:将N个数从大到小按蛇形的方式放入m行n列的矩阵,并且m*n=N,m>n,m-n最小

解题思路:先从小到大排序,然后按蛇形的方向(右下左上)填入矩阵


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>
#include <functional>

using namespace std;

#define LL long long
const int INF = 0x3f3f3f3f;

int a[10005],ans[1000][1000];
int n, r, c;
int dir[4][2] = {{-1,0},{0,1},{1,0},{ 0,-1 }};

int main()
{
	while (~scanf("%d", &n))
	{
		int c = sqrt(n);
		while (n%c != 0) c--;
		r = n / c;
		for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
		sort(a + 1, a + 1 + n,greater<int>());
		memset(ans, 0, sizeof ans);
		int x = 1, y = 1,p=0;
		for (int i = 1; i <= n; i++)
		{
			ans[x][y] = a[i];
			if (i == n) break;
			while (1)
			{
				int xx = x + dir[p][0];
				int yy = y + dir[p][1];
				if (ans[xx][yy] || xx<1 || xx>r || yy<1 || yy>c) { p++; p %= 4; continue; }
				x = xx, y = yy; break;
			}
		}
		for (int i = 1; i <= r; i++)
		{
			printf("%d", ans[i][1]);
			for (int j = 2; j <= c; j++)
				printf(" %d", ans[i][j]);
			printf("\n");
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值