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 ncolumns, 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.
Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains Npositive integers to be filled into the spiral matrix. All the numbers are no more than 1. 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.
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>
using namespace std;
bool cmp(
int a,
int b){
return a>
b;
}
int main(){
int N, i, j, n;
scanf("%d", &
N);
for(i=
1; i*i<N+
1; i++)
if(N%i==
0) n=
i;
vector<vector<
int> > arr(N/n, vector<
int>(n)), vis(N/n, vector<
int>(n,
false));
vector<
int>
v(N);
for(i=
0; i<N; i++) scanf(
"%d", &
v[i]);
sort(v.begin(), v.end(), cmp);
int x=
0, y=
0, dir=
0;
for(i=
0; i<N; i++
){
if(dir==
0){
if(y==n ||
vis[x][y]){
dir=
1;
y--
;
x++
;
i--
;
}else{
arr[x][y] =
v[i];
vis[x][y] =
true;
y++
;
}
}else if(dir==
1){
if(x==N/n ||
vis[x][y]){
x--
;
y--
;
dir=
2;
i--
;
}else{
arr[x][y] =
v[i];
vis[x][y] =
true;
x++
;
}
}else if(dir==
2){
if(y==-
1 ||
vis[x][y]){
y++
;
x--
;
dir=
3;
i--
;
}else{
arr[x][y] =
v[i];
vis[x][y] =
true;
y--
;
}
}else{
if(x==-
1 ||
vis[x][y]){
dir=
0;
x++
;
y++
;
i--
;
}else{
arr[x][y] =
v[i];
vis[x][y] =
true;
x--
;
}
}
}
for(i=
0; i<N/n; i++
){
cout<<arr[i][
0];
for(j=
1; j<n; j++) cout<<
" "<<
arr[i][j];
cout<<
endl;
}
return 0;
}
转载于:https://www.cnblogs.com/mr-stn/p/9574646.html
相关资源:垃圾分类数据集及代码