PAT (Basic Level) 1050 螺旋矩阵(模拟)

题目链接:点击查看

题目大意:给出N个数,降序排序后构造螺旋矩阵,要求行n和列m满足要求n*m==N并且n>m并且(m-n)尽可能小

题目分析:排序后就是简单的蛇形填数了,网上都是用一个while套四个while的写法,我还是喜欢用走迷宫的写法来写,这个题有个很关键的一点,就是数组大小,因为题目保证了所有数字都在1e4之内,但是如果我们要开1e4*1e4的矩阵,是肯定开不下的,这样直接交上去会有一个测试样例T掉,那我们该怎么办呢?有一个很关键的信息,就是n>m,并且(m-n)尽可能小,那么我们可以分析一下,当N最大取到1e4时,肯定将n和m分为sqrt(1e4)=100最为合适,但当N是一个大于100的质数时,此时只能分为(N,1),这是两种比较极端的情况了,到这里我们可以发现,m的值最大只能达到100,而n的值最大才可能达到1e4,所以我们开始组的时候就可以直接开maze[1e4][1e2],而不是maze[1e4][1e4]了,真的是学到了,因为这个细节调了有半个小时的代码,总是T掉,原来是数组开太大的原因

不得不说这个题目的数据也是专门卡这个点的,就看能不能想到了

代码:

#include<iostream>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<cmath>
#include<cctype>
#include<stack>
#include<queue>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<sstream> 
#include<deque>
#include<unordered_map>
#define Pi acos(-1.0)
using namespace std;

typedef long long LL;

const int inf=0x3f3f3f3f;

const int N=1e4+100;

const int b[4][2]={0,1,1,0,0,-1,-1,0};

int n,m;

int a[N];

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

void getnm(int x)
{
	int mark;
	for(int i=1;i<=sqrt(x);i++)
		if(x%i==0)
			mark=i;
	m=mark;
	n=x/mark;
}

int maze[N][100];

bool vis[N][100];

bool check(int x,int y)
{
	if(x<0||y<0||x>=n||y>=m)
		return false;
	if(vis[x][y])
		return false;
	return true;
}

int main()
{
//  freopen("input.txt","r",stdin);
    int N;
    scanf("%d",&N);
    for(int i=1;i<=N;i++)
	    scanf("%d",a+i);
    sort(a+1,a+1+N,cmp);
    getnm(N);
    int cnt=1;
    maze[0][0]=a[cnt++];
    vis[0][0]=true;
    int x=0,y=0;
    int pos=0;
    while(cnt<=N)
    {
    	int xx=x+b[pos][0];
    	int yy=y+b[pos][1];
    	while(check(xx,yy))
    	{
    		maze[xx][yy]=a[cnt++];
    		vis[xx][yy]=true;
    		x=xx;
    		y=yy;
    		xx=x+b[pos][0];
    		yy=y+b[pos][1];
		}
    	pos=(pos+1)%4;
	}
	for(int i=0;i<n;i++)
	{
		cout<<maze[i][0];
		for(int j=1;j<m;j++)
			cout<<' '<<maze[i][j];
		cout<<endl;
	}
    
    
    
    
    
    

    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Frozen_Guardian

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

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

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

打赏作者

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

抵扣说明:

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

余额充值