您的位置:首页 > 其它

1105. Spiral Matrix

2016-04-28 18:21 169 查看


1105. Spiral Matrix (25)

时间限制

150 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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 mrows 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 104. 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:
12
37 76 20 98 76 42 53 95 60 81 58 93

Sample Output:
98 95 93
42 37 81
53 20 76
58 60 76

#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;

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

int cal(int x){
int y = sqrt(x);
while(y>0){
if(x%y == 0)
return y;
--y;
}
return 1;
}

int main(){
int n,a,flag[105][105],x,y,cnt = 0,num[105][105],sx = 0,sy = 0;
vector<int> res;
cin>>n;
y = cal(n);
x = n/y;
memset(flag,-1,sizeof(flag));
for(int i = 0;i<x;++i)
for(int j = 0;j<y;++j)
flag[i][j] = 0;
for(int i = 0;i<n;++i){
cin>>a;
res.push_back(a);
}
sort(res.begin(),res.end(),cmp);
while(cnt<n){
while(sy<y && flag[sx][sy] != -1){
num[sx][sy] = res[cnt++];
flag[sx][sy] = -1;
++sy;
}
--sy;
++sx;
while(sx<x && flag[sx][sy] != -1){
num[sx][sy] = res[cnt++];
flag[sx][sy] = -1;
++sx;
}
--sx;
--sy;
while(sy>=0 && flag[sx][sy] != -1){
num[sx][sy] = res[cnt++];
flag[sx][sy] = -1;
--sy;
}
++sy;
--sx;
while(sx>=0 && flag[sx][sy] != -1){
num[sx][sy] = res[cnt++];
flag[sx][sy] = -1;
--sx;
}
++sx;
++sy;
}
for(int i = 0;i<x;++i){
cout<<num[i][0];
for(int j = 1;j<y;++j)
cout<<" "<<num[i][j];
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: