本题要求将给定的 N 个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第 1 个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为 m 行 n 列,满足条件:m×n 等于 N;m≥n;且 m−n 取所有可能值中的最小值。
输入格式:
输入在第 1 行中给出一个正整数 N,第 2 行给出 N 个待填充的正整数。所有数字不超过 104,相邻数字以空格分隔。
输出格式:
输出螺旋矩阵。每行 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<string>
using namespace std;
#include<math.h>
#include<algorithm>
int arr[1000000];
int shuchu[10000][10000];
int cmp(int a, int b);
int main() {
int N;
cin >> N;
int m, n;
for (int cnt = 0; cnt < N; cnt++) {
cin >> arr[cnt];
}
sort(arr, arr + N,cmp);
for (int cnt = sqrt((double)N); cnt >= 1; cnt--) {
if (N % cnt == 0) {
n = cnt;
m = N / cnt;
break;
}
}
int i = 0;
for (int cnt = 0; cnt < m / 2 + m % 2; cnt++) {
for (int cnt1 = cnt; cnt1 < n - cnt && i<N; cnt1++)
shuchu[cnt][cnt1] = arr[i++];
for (int cnt1 = cnt+1; cnt1 < m - 1 - cnt && i < N ; cnt1++)
shuchu[cnt1][n - 1 - cnt] = arr[i++];
for (int cnt1 = n - 1 - cnt; cnt1 >= cnt && i < N; cnt1--)
shuchu[m - 1 - cnt][cnt1] = arr[i++];
for (int cnt1 = m-2-cnt; cnt1 >=cnt+1 && i < N ; cnt1--)
shuchu[cnt1][cnt] = arr[i++];
}
for (int cnt = 0; cnt < m; cnt++) {
for (int cnt1 = 0; cnt1 < n; cnt1++) {
printf("%d",shuchu[cnt][cnt1]);
if (cnt1 != n - 1)printf(" ");
}
cout << endl;
}
return 0;
}
int cmp(int a, int b) {
return a > b;
}
我踩过的坑,这题如果出现了格式错误,注意下是不是行列反了,还有个特征就是,两个格式错误,一个答案错误,基本就是行列搞混了导致的