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

AC代码

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

int main(){
	int N;
	cin>>N;
	vector<int> num(N);
	for(int i = 0; i < N; i++)
		cin>>num[i];
	sort(num.begin(), num.end());
	int m = (int)sqrt(1.0 * N), n; //矩阵行列数
	while(m <= N){
		if(N % m == 0){
			n = N / m;
			if(m >= n) break;
		}
		m++;		
	}
	int a = m, b = n;
	int matrix[m + 1][n + 1];
	int i = N - 1, start = 0;
	while(m > 0 && n > 0){
		for(int j = 0; i >= 0 && j < n; j++)
			matrix[start][start + j] = num[i--];
		for(int j = 1; i >= 0 && j < m; j++)
			matrix[start + j][start + n - 1] = num[i--];
		for(int j = n - 2; i >= 0 && j >= 0; j--)
			matrix[start + m - 1][start + j] = num[i--];
		for(int j = m - 2; i >= 0 && j > 0; j--)
			matrix[start + j][start] = num[i--];
		start++;
		n -= 2;
		m -= 2;
	}
	for(int i = 0; i < a; i++){
		for(int j = 0; j < b; j++){
			cout<<matrix[i][j];
			if(j == b - 1) cout<<endl;
			else cout<<" ";
		}
	}
	return 0;
}
发布了110 篇原创文章 · 获赞 0 · 访问量 1249

猜你喜欢

转载自blog.csdn.net/qq_43072010/article/details/105556902