PTA 1105 Spiral Matrix (25 分)
1105 Spiral Matrix (25 分)
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
感悟
這種矩陣的題總是x,y座標弄混,a[i][j],i代表第幾行,j代表第幾列,這題找找數學規律,i和j的座標一定是符合數學規律的,但是我懶,因為題目中告訴了資料一定是正整數所以,初值賦為0,剛好用來判重,每次都從頭走到底,遍歷四輪,如果當前座標的元素值為0代表沒用過,就可以賦值,如果不為零,代表走過,continue就好.PAT能用碼量不大的樸素演算法AC就用樸素演算法,除非卡了時間複雜度或者碼量差別很大,再考慮優化.
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10010;
int a[N];
int x, y, res = 0x3f3f3f3f;
int main()
{
int n;
scanf("%d", &n);
for(int i = 1 ; i <= n ; i ++) scanf("%d", &a[i]);
sort(a+1,a+n+1,greater<int>());
for(int i = 1 ; i * i <= n ; i ++)
{
int j = n / i;
if(n % i) continue;
res = min(res,(j-i));
if(res == j - i) x = i, y = j;
}
int b[y+1][x+1] ={0};
int cnt = 1, l = 1;
while(cnt <= n)
{
int lx = x - l,ly = y - l;
for(int i = l ; i <= x ; i ++)
if(!b[l][i]) b[l][i] = a[cnt++];
for(int i = 1 ; i <= y ; i ++)
if(!b[i][x-l+1]) b[i][x-l+1] = a[cnt++];
for(int i = x-l+1 ; i >= 1 ; i --)
if(!b[y-l+1][i]) b[y-l+1][i] = a[cnt++];
for(int i = y-l+1 ; i >= 1 ; i --)
if(!b[i][l]) b[i][l] = a[cnt++];
l++;
}
for(int i = 1 ;i <= y ; i ++)
for(int j = 1 ; j <= x ; j ++)
printf("%d%c",b[i][j],j == x ? '\n' : ' ');
return 0;
}