本题要求将给定的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 <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int m=0,n=0,p=10000;
void mn(int N){ //计算m , n的值
for(int i=2; i<=sqrt(N) ;i++){
if(N % i == 0){
int j = N /i;
int q = j -i; //m,n之间的差值
if(q<p){
m = j;
n = i;
p = q;
}
}
}
}
void Show(int **p,int m, int n){ //显示结果
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(j==0)
cout<<p[i][j];
else{
cout<<" "<<p[i][j];
}
}
cout<<endl;
}
}
void Rec(int **res,int m,int n, vector<int> V){//、构造螺旋矩阵
//int small = m >=n ? n :m;
vector<int>::iterator it = V.begin();
int count = n / 2;
for(int i=0;i<count;i++){
int R = m -1 - i;
int C = n -1 - i;
for(int j=i;j<C;j++){
res[i][j] = *it;
it++;
//cout<<"yes"<<endl;
}
for(int j=i;j<R;j++){
res[j][C] = *it;
it++;
//out<<"ok"<<endl;
}
for(int j=C;j>i;j--){
res[R][j] = *it;
it++;
//cout<<"good"<<endl;
}
for(int j=R;j>i;j--){
res[j][i] = *it;
if(it != V.end())
it++;
//cout<<"nice"<<endl;
}
}
if(n & 1){ //说明最后又1*k或者k*1的矩阵
int i = count;
for(int j= i;j<m-i;++j){
res[j][i] = *it;
if(it != V.end())
it++;
}
}
}
bool isPrime(int N){
for(int i=2;i<=sqrt(N);i++){
if(N % i == 0)
return false;
}
return true;
}
int main()
{
int N;
cin>>N;
if(N == 1)
{
int tmp;
cin>>tmp;
cout<<tmp<<endl;
return 0;
}
if(isPrime(N)){
//cout<<"N is primer number!"<<endl;
vector<int> Vec;
for(int i=0;i<N;i++){
int tmp ;
cin>>tmp;
Vec.push_back(tmp);
}
sort(Vec.begin(),Vec.end(),greater<int>());
vector<int>::iterator its = Vec.begin();
while(its != Vec.end()){
cout<<*its<<endl;
its++;
}
return 0;
}
vector<int> V;
for(int i=0 ;i<N; i++)
{
int tmp;
cin>>tmp;
V.push_back(tmp);
}
sort(V.begin(),V.end(),greater<int>());
mn(N);//找出最差值最小的m n的值
//cout<<"m ,n"<<m<<" "<<n<<endl;
// vector<int>::iterator it = V.begin();
// int count=0;
// while(it != V.end()){
// count++;
// if(count % n ==0){
// cout<<*it<<endl;
// }else{
// cout<<*it<<" ";
// }
// ++it;
// }
// cout<<endl;
//定义一个二维数组
int **res = new int *[n+1];
//如果设定 int **res = new int*(n) 当N 为10 和14 会发生段错误 我也不知道为什么
for(int i=0;i<m;i++){
res[i] = new int[n+1];
}
// for(int i=0;i<m;i++){
// for(int j=0;j<n;j++){
// res[i][j]=0;
// cout<<res[i][j]<<" ";
// }
// cout<<endl;
// }
Rec(res, m, n,V);
Show(res,m,n);
return 0;
}
Aden:首先对其给个个数N求出满足条件的m和n,这样就可以确定自己所需要的二维矩阵的规模了,然后再构造螺旋矩阵,注意一定要对最后可能留存的k*1或者1*k个元素专门处理。