美文网首页
PAT甲级A1105---快乐模拟

PAT甲级A1105---快乐模拟

作者: 1nvad3r | 来源:发表于2020-09-14 15:57 被阅读0次

1105 Spiral Matrix (25分)

1105
分析:

将N个数逆时针螺旋填入矩阵中,由于行数m * 列数n 要等于N,所以m为N的约数。又m≥n,且m-n最小,可以先令m等于根号N,然后往上找第一个N的约数。
令U,D,L,R代表上下左右四个边界,i,j代表正在填充的行数和列数,每填充完一层之后,就令边界缩小1个数,然后把i和j加到下一层第一个数继续填充。
注意特判N等于1时,直接输出。如果只剩最后中间一个数时,也要输出。

C++:
#include <cstdio>
#include <algorithm>
#include <cmath>

using namespace std;

const int maxn = 100010;
int A[maxn];
int matrix[maxn][maxn];

bool cmp(int a, int b) {
    return a > b;
}

int main() {
    int N;
    scanf("%d", &N);
    for (int i = 0; i < N; i++) {
        scanf("%d", &A[i]);
    }
    if (N == 1) {
        printf("%d", A[0]);
        return 0;
    }
    sort(A, A + N, cmp);
    int m = ceil(sqrt(1.0 * N));
    while (N % m != 0) {
        m++;
    }
    int n = N / m, i = 1, j = 1, now = 0;
    int U = 1, D = m, L = 1, R = n;//4个边界
    while (now < N) {
        while (now < N && j < R) {
            matrix[i][j] = A[now++];
            j++;
        }
        while (now < N && i < D) {
            matrix[i][j] = A[now++];
            i++;
        }
        while (now < N && j > L) {
            matrix[i][j] = A[now++];
            j--;
        }
        while (now < N && i > U) {
            matrix[i][j] = A[now++];
            i--;
        }
        U++, D--, L++, R--;
        i++, j++;
        if (now == N - 1) {
            matrix[i][j] = A[now++];
        }
    }
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            printf("%d", matrix[i][j]);
            if (j < n) {
                printf(" ");
            } else {
                printf("\n");
            }
        }
    }
    return 0;
}

相关文章

  • PAT甲级A1105---快乐模拟

    1105 Spiral Matrix (25分) 分析: 将N个数逆时针螺旋填入矩阵中,由于行数m * 列数n 要...

  • PAT A1001 A+B Format (20)

    PAT A1001 A+B Format 原题链接PAT甲级题目目录(简书)PAT甲级题目目录(CSDN)在CSD...

  • 字符串输入问题

    PAT 甲级 1100 People on Mars count their numbers with base ...

  • PAT甲级题解 全部 JAVA版 持续更新

      临近过年,闲来无事。恰逢弟弟准备考PAT甲级,总是问我一些问题。又见网上PAT甲级多为c/c++版本的答案。罕...

  • PAT甲级 1043 Is It a Binary Search

    原题链接 PAT甲级 1043 Is It a Binary Search Tree (25 分) 题目大意 给定...

  • 2020-02-06

    PAT-甲级 做题笔记 目录 0000 做题 Tips 基本经验1003 Emergency (Dijkstra ...

  • Pat 甲级 1001

    太感人终于把1001做对了,一开始没有看清题目要求。产生各种各样的错误,最后又有编译错误。在Pat中Java的类名...

  • Pat 甲级1002

    在编译器中将边界设为1001 然后提交的代码边界设为1000,结果产生了部分正确的结果,实在是不应该,浪费太多时间...

  • PAT甲级题目

    先把会做的做了,emmmm 1006 水题,关键就是在于如何切分字符串而已,考的应该也就是字符串了: 1007 这...

  • PAT甲级1006

    1006 Sign In and Sign Out (25分)At the beginning of every ...

网友评论

      本文标题:PAT甲级A1105---快乐模拟

      本文链接:https://www.haomeiwen.com/subject/fuuzektx.html