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;
}
posted @ 2022-03-03 13:54  别问了我什么都不会  阅读(22)  评论(0编辑  收藏  举报