LoKwongho

mm

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; mn; and mn 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

 

知识点:简单模拟;vector的使用
思路:
矩阵应该利用vector的数组来构建;因为如果是形成比较方正的矩阵,长和宽最大是100左右;但如果是质数,矩阵就会变成长条形长在10000以内,这样利用普通二维数组数组会超限;利用了vector容器可以.resize()的特点。
单列的输出特殊处理

 1 #include <iostream>
 2 #include <string>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <vector>
 6 using namespace std;
 7 const int maxn = 1000;
 8 
 9 vector<int> matrix[maxn];
10 
11 bool cmp(int a,int b){
12     return a>b;
13 }
14 
15 int getLong(int n){
16     int i;
17     for(i=sqrt(n)+0.9;i<=n && n%i!=0;i++);
18     return i;
19 }
20 
21 int main(){
22     vector<int> list;
23     int n,tmp; cin >> n;
24     for(int i=0;i<n;i++){
25         scanf("%d",&tmp);
26         list.push_back(tmp);
27     }
28     sort(list.begin(), list.end(), cmp);
29     int l = getLong(n);
30     int w = n/l;
31     for(int i=1;i<=l;i++){
32         matrix[i].resize(w+1);
33     }
34     int x=1, y=1, ptr=0;
35 
36     int base=0;
37     while(ptr<list.size()){
38         if(w==1){
39             for(;y<=l+base;y++){
40                 matrix[y][x]=list[ptr++];
41             }
42             break;
43         }
44         for(; x<=w+base; x++){
45             
46             matrix[y][x]=list[ptr++];
47         }
48         
49         x--; y++;
50         for(; y<l+base; y++){
51             matrix[y][x]=list[ptr++];
52         }        
53         for(; x>=1+base; x--){
54             matrix[y][x]=list[ptr++];
55         }
56         x++; y--;
57         for(; y>1+base; y--){
58             matrix[y][x]=list[ptr++];
59         }
60         x++; y++;
61         w-=2; l-=2;
62         base++;
63         //printf("%d %d w=%d l=%d",x,y,w,l);
64         
65     }
66     for(int i=1;i<=getLong(n);i++){
67         for(int j=1;j<=(n/getLong(n));j++){
68             if(j!=1) printf(" ");
69             printf("%d",matrix[i][j]);
70         }
71         printf("\n");
72     }
73 }

 

posted on 2018-11-09 10:52  iojafekniewg  阅读(215)  评论(0编辑  收藏  举报

导航

My Email guangho2743##foxmail.com : )