1105 Spiral Matrix

时间:2023-03-09 03:14:06
1105 Spiral Matrix

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 10​4​​. 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:


Sample Output:

  

  
知识点:简单模拟;vector的使用
思路:
矩阵应该利用vector的数组来构建;因为如果是形成比较方正的矩阵,长和宽最大是100左右;但如果是质数,矩阵就会变成长条形长在10000以内,这样利用普通二维数组数组会超限;利用了vector容器可以.resize()的特点。
单列的输出特殊处理
 #include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
const int maxn = ; vector<int> matrix[maxn]; bool cmp(int a,int b){
return a>b;
} int getLong(int n){
int i;
for(i=sqrt(n)+0.9;i<=n && n%i!=;i++);
return i;
} int main(){
vector<int> list;
int n,tmp; cin >> n;
for(int i=;i<n;i++){
scanf("%d",&tmp);
list.push_back(tmp);
}
sort(list.begin(), list.end(), cmp);
int l = getLong(n);
int w = n/l;
for(int i=;i<=l;i++){
matrix[i].resize(w+);
}
int x=, y=, ptr=; int base=;
while(ptr<list.size()){
if(w==){
for(;y<=l+base;y++){
matrix[y][x]=list[ptr++];
}
break;
}
for(; x<=w+base; x++){ matrix[y][x]=list[ptr++];
} x--; y++;
for(; y<l+base; y++){
matrix[y][x]=list[ptr++];
}
for(; x>=+base; x--){
matrix[y][x]=list[ptr++];
}
x++; y--;
for(; y>+base; y--){
matrix[y][x]=list[ptr++];
}
x++; y++;
w-=; l-=;
base++;
//printf("%d %d w=%d l=%d",x,y,w,l); }
for(int i=;i<=getLong(n);i++){
for(int j=;j<=(n/getLong(n));j++){
if(j!=) printf(" ");
printf("%d",matrix[i][j]);
}
printf("\n");
}
}