PAT 1105. Spiral Matrix (25)

1105. Spiral Matrix (25)

時間限制
150 ms
內存限制
65536 kB
代碼長度限制
16000 B
判題程序
Standard
作者
CHEN, Yue

This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrixis 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.

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

這道題首先是要類似分解因數並找到兩個因數之差最小的,然後我是用模擬螺旋前進的方式構建矩陣,用了switch來判斷前進方向。 

代碼如下: 

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
int N;
vector<int> rawInput;
typedef struct{
	int m;
	int n;
}info;
int cmp(const info a, const info b){
	return a.m - a.n < b.m - b.n;
}
info findMN(){
	vector<info> tmp;
	for(int i = 1; i <= N; i++){
		for(int j = 1; j <= i; j++){
			if(i*j == N){
				info infoTmp;
				infoTmp.m = i;
				infoTmp.n = j;
				tmp.push_back(infoTmp);
			}
		}
	}
	sort(tmp.begin(),tmp.end(),cmp);
	return tmp[0];
}
int main(void)
{
	cin>>N;
	rawInput.resize(N);
	for(int i = 0; i < N; i++)
		scanf("%d",&rawInput[i]);
	sort(rawInput.begin(),rawInput.end(),greater<int>());
	info infoResult = findMN();
	int m = infoResult.m;
	int n = infoResult.n;
	vector<vector<int> > matrix(m);
	for(int i = 0; i < matrix.size(); i++)
		matrix[i].resize(n);
	int row = 0,column = 0;
	int dirction = 0;
	for(int i = 0; i < N; i++){
		switch(dirction % 4){
			case 0: matrix[row][column] = rawInput[i];
					if(++column >= n - dirction/4){
						column--;
						row++;
						dirction++;
					}
					break;
			case 1: matrix[row][column] = rawInput[i];
					if(++row >= m - dirction/4){
						row--;
						column--;
						dirction++;
					}
					break;
			case 2: matrix[row][column] = rawInput[i];
					if(--column < dirction/4){
						column++;
						row--;
						dirction++;
					}
					break;
			case 3: matrix[row][column] = rawInput[i];
					if(--row < 1 + dirction/4){
						row++;
						column++;
						dirction++;
					}
		}
	}
	for(int i = 0; i < m; i++){
		for(int j = 0; j < n; j++){
			if(j) 
				cout<<" "<<matrix[i][j];
			else
				cout<<matrix[i][j];
		}
		cout<<endl;
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章