您的位置:首页 > 其它

PAT-A-1050. 螺旋矩阵(25)

2017-06-18 23:18 393 查看


1050. 螺旋矩阵(25)

时间限制

150 ms

内存限制

65536 kB

代码长度限制

8000 B

判题程序

Standard

作者

CHEN, Yue

本题要求将给定的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<cstdio>
#include<math.h>
#include<algorithm>

using namespace std;
const int maxn = 10010;

int a[maxn];
int b[maxn][maxn];

int cmp(int a, int b)
{
return a > b;
}
int main()
{
int num;
cin >> num;
for (int i = 0; i < num; i++)
cin >> a[i];

if (num == 1)
{
cout << a[0];
return 0;
}

int sqr = (int)ceil(sqrt(1.0*num));

int m = sqr;
while (num % m != 0)
{
m++;
}
int n = num / m;
sort(a, a + num, cmp);

int now = 0;

int u = 1, d = m, l = 1, r = n;
int i = 1, j = 1;
while (now < num)
{
while (j < r&&now < num)
{
b[i][j] = a[now];
now++;
j++;
}

while (i < d&&now < num)
{
b[i][j] = a[now];
now++;
i++;
}

while (j>l&&now < num)
{
b[i][j] = a[now];
now++;
j--;
}

while (i>u&&now < num)
{
b[i][j] = a[now];
now++;
i--;
}

r--;
l++;
u++;
d--;
i++;
j++;

if (now == num - 1)
{
b[i][j] = a[now];
now++;
}

}

for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
cout << b[i][j];

if (j != n)
cout << " ";

}
cout << endl;
}

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: