PAT 1105. Spiral Matrix (25)

来源:互联网 发布:淘宝服装店女装推荐 编辑:程序博客网 时间:2024/06/03 07:16

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:
1237 76 20 98 76 42 53 95 60 81 58 93
Sample Output:
98 95 9342 37 8153 20 7658 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];elsecout<<matrix[i][j];}cout<<endl;}return 0;}


0 0
原创粉丝点击