题目链接:点击查看
题目大意:给出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;
}