标签:nta val its must more swap file sample inpu
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 10?4??. 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
添加4个边界up, down, left , right,这个题此时就很好处理了
注意设置的边界线 right = m -1, up = n - 1, 因此 在处理从左到右时 i可以 = right 处理从上到下 i 可以 = down;
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int main()
{
int sum;
vector<int> v;
scanf("%d", &sum);
int m = sqrt(sum);
while(m * (sum / m) != sum) m++;
int n = sum / m, num;
if(n > m) swap(n, m);
for(int i = 0; i < sum; i++) {
scanf("%d", &num);
v.push_back(num);
}
sort(v.begin(), v.end(), cmp);
int edge[m + 1][n + 1];
int cnt = 0, l = 0, r = n - 1, u = 0, d = m - 1;
while(cnt < sum) {
for(int i = l; i <= r && cnt < sum; i++) edge[u][i] = v[cnt++];
u++;
for(int i = u; i <= d && cnt < sum; i++) edge[i][r] = v[cnt++];
r--;
for(int i = r; i >= l && cnt < sum; i--) edge[d][i] = v[cnt++];
d--;
for(int i = d; i >= u && cnt < sum; i--) edge[i][l] = v[cnt++];
l++;
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
printf("%s%d", j == 0? "" : " ", edge[i][j]);
}
puts("");
}
}
标签:nta val its must more swap file sample inpu
原文地址:https://www.cnblogs.com/csyxdh/p/12466355.html