1105. Spiral Matrix (25)

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 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

 1 #include<stdio.h>
 2 #include<vector>
 3 #include<algorithm>
 4 #include<math.h>
 5 using namespace std;
 6 int ans[111][111];
 7 
 8 bool cmp(int a,int b)
 9 {
10     return a > b;
11 }
12 int main()
13 {
14     int len,tem;
15     scanf("%d",&len);
16     vector<int> vv;
17     for(int i = 1 ;i <= len ;++i)
18     {
19         scanf("%d",&tem);
20         vv.push_back(tem);
21     }
22     sort(vv.begin(),vv.end(),cmp);
23     int n,m;
24     n = sqrt((double)len);
25     while(len % n != 0)
26     {
27         --n;
28     }
29     m = len / n;
30     int high = 1, low = m, left = 1,right = n;
31     int  x = 1,y = 1;
32     for(int i = 0 ;i < len ;++i)
33     {
34         while(i < len && x <= right)
35         {
36             ans[y][x] = vv[i];
37             ++i;
38             ++x;
39         }
40         --x;
41         ++y;
42         ++high;
43         while(i < len && y <= low)
44         {
45             ans[y][x] = vv[i];
46             ++i;
47             ++y;
48         }
49         --y;
50         --x;
51         --right;
52         while(i < len && x >= left)
53         {
54             ans[y][x] = vv[i];
55             ++i;
56             --x;
57         }
58         ++x;
59         --y;
60         --low;
61         while(i < len && y >= high)
62         {
63             ans[y][x] = vv[i];
64             ++i;
65             --y;
66         }
67         ++y;
68         ++x;
69         ++left;
70         --i;
71     }
72     for(int i = 1 ;i <= m ;++i)
73     {
74         for(int k = 1 ;k <= n ;++k)
75         {
76             if(k == 1) printf("%d",ans[i][k]);
77             else printf(" %d",ans[i][k]);
78         }
79         printf("\n");
80     }
81     return 0;
82 }

 

你可能感兴趣的:(1105. Spiral Matrix (25))