PTA螺旋矩阵 (25分)

it2023-12-23  80

“人其实就这一辈子,我想要的生活不是安逸的,虽然很累,但我想要辉煌的人生,所以也一直在为此努力、不松懈。我所理解的辉煌人生,不是挣了多少钱、做了多伟大的事,而是将人生过得有意义,不碌碌无为。哪怕前进得很慢,但是每分每秒都在往前走,去追求梦想。”                                                                                                                               ----喻言

本题要求将给定的 N 个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第 1 个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为 m 行 n 列,满足条件:m×n 等于 N;m≥n;且 m−n 取所有可能值中的最小值。

输入格式:

输入在第 1 行中给出一个正整数 N,第 2 行给出 N 个待填充的正整数。所有数字不超过 10​4​​,相邻数字以空格分隔。

输出格式:

输出螺旋矩阵。每行 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 <algorithm> #include <string> #include <cstring> #include <cstdlib> #include <cmath> #include <stack> #include <queue> #include <set> #include <map> #include <vector> #include <ctime> #include <cctype> #include <bitset> #include <utility> #include <sstream> #include <complex> #include <iomanip> #include <numeric> #include<unordered_set> #include <climits>//INT_100010n //#include<bits/stdc++.h> #define PP pair<ll,int> #define inf 0x3f3f3f3f #define INF 0x7fffffff; #define llinf 0x3f3f3f3f3f3f3f3fll #define dinf 1000000000000.0 #define PI 3.1415926 #define LL unsigned int #define mod 1000000007 #define wc 1e-8 typedef long long ll; using namespace std; int n; int main() { scanf("%d",&n); int a[n]; for(int i=0; i<n; i++) scanf("%d",&a[i]); sort(a,a+n); int x=sqrt(n),m; while(n%x) { x--; } m=n/x; int t[m][x]; for(int ls=0,k=n-1; ls*2<x; ls++) { for(int j=ls; j<x-ls; j++) t[ls][j]=a[k--]; for(int i=ls+1; i<m-ls; i++) t[i][x-1-ls]=a[k--]; for(int j=x-2-ls; j>=ls; j--) t[m-1-ls][j]=a[k--]; if(x-1-ls>ls) { for(int i=m-2-ls; i>=ls+1; i--) { t[i][ls]=a[k--]; } } } for(int i=0; i<m; i++) { for(int j=0; j<x; j++) { printf("%d",t[i][j]); if(j+1<x) printf(" "); } printf("\n"); } return 0; }

 

最新回复(0)