[pat]1105. Spiral Matrix (25)

https://www.patest.cn/contests/pat-a-practise/1105

#pragma warning(disable:4996)
#include<vector>
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;

bool cmp(int a, int b){
	return a > b;
}
int res[200][200];
int main(){
	int n;
	int i, j, k;
	cin>>n;
	vector<int> vn;
	for(i = 0; i < n; i++){
		int a;
		cin>>a;
		vn.push_back(a);
	}
	sort(vn.begin(), vn.end(), cmp);

	int col = sqrt(n);
	int row = col+1 ;
	while(n % col) col--;
	row = n / col;
	int rbegin = 1, rend = row;
	int cbegin = 1, cend = col;
	i = 0;
	int r = 1, c = 1;
	int mcase = 1;
	while(i < vn.size()){
		switch(mcase){
		case 1:
			for(c = cbegin; c <= cend && i < vn.size(); c++){
				res[r][c] = vn[i++];
			}
			c--;
			mcase = 2;
			rbegin++;
			break;
		case 2:
			for(r = rbegin; r <= rend && i < vn.size(); r++){
				res[r][c] = vn[i++];
			}
			r--;
			mcase = 3;
			cend--;
			break;
		case 3:
			for(c = cend; c >= cbegin && i < vn.size(); c--){
				res[r][c] = vn[i++];
			}
			c++;
			mcase = 4;
			rend--;
			break;
		case 4:
			for(r = rend; r >= rbegin && i < vn.size(); r--){
				res[r][c] = vn[i++];
			}
			r++;
			mcase = 1;
			cbegin++;
			break;
		}

		if(rbegin > rend || cbegin > cend) break;  
	}
	for(int i = 1; i <= row; i++){
		if(i != 1) printf("\n");
		for(int j = 1; j <= col; j++){
			if(j != 1) printf(" ");
			printf("%d", res[i][j]);
		}
	}

	system("pause");
	return 0;
}


你可能感兴趣的:(pat,OJ)