1.题目
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 n columns, 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
2.题目分析
PAT (Basic Level) Practice 1050 螺旋矩阵 (25分) (数组标记、内存使用)
3.代码
#include<iostream>
#include<algorithm>
#include<cmath>
#include<functional>
using namespace std;
int out[10001][10001],/*mark[10001][10001],*/list[10001];
int main()
{
int num;
cin >> num;
for (int i = 0; i < num; i++)
cin >> list[i];
int m, n;
for (int i = sqrt(num); i >= 1;i--)
if (num%i == 0) { n = i; m = num / n; break; }
sort(list, list + num,greater<int>());
int round = 0;
int count = 0;
while(count!=num)
{
for (int j = 0; j < n; j++)
{
if (out[round][j] != 0)continue;
//if(mark[round][j] == 1)continue;
out[round][j] = list[count++];
//mark[round][j] = 1;
}
for (int j = 0; j < m; j++)
{
if (out[j][n - 1 - round] != 0)continue;
//if (mark[j][n - 1 - round] ==1)continue;
out[j][n - 1 - round] = list[count++];
//mark[j][n - 1 - round] =1;
}
for (int j = n - 1; j >= 0; j--)
{
if (out[m - 1 - round][j] != 0)continue;
//if (mark[m - 1 - round][j] ==1)continue;
out[m - 1 - round][j] = list[count++];
//mark[m - 1 - round][j] = 1;
}
for (int j = m - 1; j >= 0; j--)
{
if (out[j][round] != 0)continue;
//if (mark[j][round] ==1)continue;
out[j][round] = list[count++];
//mark[j][round] = 1;
}
round++;
}
int space = 0;
for (int i = 0; i < m; i++)
{
space = 0;
for (int j = 0; j < n; j++)
{
if (space == 0) { cout << out[i][j]; space++; }
else cout << ' ' << out[i][j];
}
cout << endl;
}
}